diff --git a/TODO b/TODO index ffadc06d..7aa4de1a 100644 --- a/TODO +++ b/TODO @@ -1,59 +1,59 @@ # What's left to do -*- org -*- * Next API break: ** gcry_ac_io_t Remove use of anonymous union. ** gcry_ac Consider to remove it. * udiv-qrnbd.o should get build as *.lo [HPUX] * Allow operation using RSA keys consisting of the OpenSSL keys. This requires the introduction of a parameter names (say) U which is calculated according to OpenSSL/PKCS#1 rules. * linker script test Write an autoconf test to check whether the linker supports a version script. * Add attributes to the MPI functions. -* cipher/pubkey.c and pubkey implementaions. +* cipher/pubkey.c and pubkey implementations. Don't rely on the secure memory based wiping function but add an extra wiping. * Use builtin bit functions of gcc 3.4 * Consider using a daemon to maintain the random pool [Partly done] The down side of this is that we can't assume that the random has has always been stored in "secure memory". And we rely on that sniffing of Unix domain sockets is not possible. We can implement this simply by detecting a special prefixed random seed name and divert in this case to the daemon. There are several benefits with such an approach: We keep the state of the RNG over invocations of libgcrypt based applications, don't need time consuming initialization of the pool and in case the entropy collectros need to run that bunch of Unix utilities we don't waste their precious results. * gcryptrnd.c Requires a test for pth [done] as well as some other tests. * secmem.c Check whether the memory block is valid before releasing it and print a diagnosic, like glibc does. * threads ** We need to document fork problems In particular that reinitialization is required in random.c However, there is no code yet to do it. * Tests We need a lot more tests. Lets keep an ever growing list here. ** Write tests for the progress function ** mpitests does no real checks yet. ** pthreads To catch simple errors like the one fixed on 2007-03-16. ** C++ tests We have some code to allow using libgcrypt from C++, so we also should have a test case. diff --git a/acinclude.m4 b/acinclude.m4 index dcdadfd3..fc208c53 100644 --- a/acinclude.m4 +++ b/acinclude.m4 @@ -1,396 +1,396 @@ dnl macros to configure Libgcrypt dnl Copyright (C) 1998, 1999, 2000, 2001, 2002, dnl 2003 Free Software Foundation, Inc. dnl Copyright (C) 2013 g10 Code GmbH dnl dnl This file is part of Libgcrypt. dnl dnl Libgcrypt is free software; you can redistribute it and/or modify dnl it under the terms of the GNU Lesser General Public License as dnl published by the Free Software Foundation; either version 2.1 of dnl the License, or (at your option) any later version. dnl dnl Libgcrypt is distributed in the hope that it will be useful, dnl but WITHOUT ANY WARRANTY; without even the implied warranty of dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the dnl GNU Lesser General Public License for more details. dnl dnl You should have received a copy of the GNU Lesser General Public dnl License along with this program; if not, write to the Free Software dnl Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA dnl GCRY_MSG_SHOW(PREFIX,STRING) dnl Print a message with a prefix. dnl define([GCRY_MSG_SHOW], [ echo " $1 $2" 1>&AS_MESSAGE_FD([]) ]) dnl GCRY_MSG_WRAP(PREFIX, ALGOLIST) dnl Print a nicely formatted list of algorithms -dnl with an approriate line wrap. +dnl with an appropriate line wrap. dnl define([GCRY_MSG_WRAP], [ tmp=" $1" tmpi="abc" if test "${#tmpi}" -ne 3 >/dev/null 2>&1 ; then dnl Without a POSIX shell, we don't botter to wrap it echo "$tmp $2" 1>&AS_MESSAGE_FD([]) else tmpi=`echo "$tmp"| sed 's/./ /g'` echo $2 EOF | tr ' ' '\n' | \ while read word; do if test "${#tmp}" -gt 70 ; then echo "$tmp" 1>&AS_MESSAGE_FD([]) tmp="$tmpi" fi if test "$word" = "EOF" ; then echo "$tmp" 1>&AS_MESSAGE_FD([]) else tmp="$tmp $word" fi done fi ]) dnl GNUPG_CHECK_TYPEDEF(TYPE, HAVE_NAME) dnl Check whether a typedef exists and create a #define $2 if it exists dnl AC_DEFUN([GNUPG_CHECK_TYPEDEF], [ AC_MSG_CHECKING(for $1 typedef) AC_CACHE_VAL(gnupg_cv_typedef_$1, [AC_TRY_COMPILE([#define _GNU_SOURCE 1 #include #include ], [ #undef $1 int a = sizeof($1); ], gnupg_cv_typedef_$1=yes, gnupg_cv_typedef_$1=no )]) AC_MSG_RESULT($gnupg_cv_typedef_$1) if test "$gnupg_cv_typedef_$1" = yes; then AC_DEFINE($2,1,[Defined if a `]$1[' is typedef'd]) fi ]) dnl GNUPG_CHECK_GNUMAKE dnl AC_DEFUN([GNUPG_CHECK_GNUMAKE], [ if ${MAKE-make} --version 2>/dev/null | grep '^GNU ' >/dev/null 2>&1; then : else AC_MSG_WARN([[ *** *** It seems that you are not using GNU make. Some make tools have serious *** flaws and you may not be able to build this software at all. Before you *** complain, please try GNU make: GNU make is easy to build and available *** at all GNU archives. It is always available from ftp.gnu.org:/gnu/make. ***]]) fi ]) # # GNUPG_SYS_SYMBOL_UNDERSCORE # Does the compiler prefix global symbols with an underscore? # # Taken from GnuPG 1.2 and modified to use the libtool macros. AC_DEFUN([GNUPG_SYS_SYMBOL_UNDERSCORE], [tmp_do_check="no" case "${host}" in i?86-mingw32* | i?86-*-mingw32*) ac_cv_sys_symbol_underscore=yes ;; x86_64-*-mingw32*) ac_cv_sys_symbol_underscore=no ;; i386-emx-os2 | i[3456]86-pc-os2*emx | i386-pc-msdosdjgpp) ac_cv_sys_symbol_underscore=yes ;; *) if test "$cross_compiling" = yes; then if test "x$ac_cv_sys_symbol_underscore" = x ; then ac_cv_sys_symbol_underscore=yes fi else tmp_do_check="yes" fi ;; esac if test "$tmp_do_check" = "yes"; then AC_REQUIRE([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE]) AC_MSG_CHECKING([for _ prefix in compiled symbols]) AC_CACHE_VAL(ac_cv_sys_symbol_underscore, [ac_cv_sys_symbol_underscore=no cat > conftest.$ac_ext < $ac_nlist) && test -s "$ac_nlist"; then # See whether the symbols have a leading underscore. if egrep '^_nm_test_func' "$ac_nlist" >/dev/null; then ac_cv_sys_symbol_underscore=yes else if egrep '^nm_test_func ' "$ac_nlist" >/dev/null; then : else echo "configure: cannot find nm_test_func in $ac_nlist" >&AC_FD_CC fi fi else echo "configure: cannot run $lt_cv_sys_global_symbol_pipe" >&AC_FD_CC fi else echo "configure: failed program was:" >&AC_FD_CC cat conftest.c >&AC_FD_CC fi rm -rf conftest* ]) else AC_MSG_CHECKING([for _ prefix in compiled symbols]) fi AC_MSG_RESULT($ac_cv_sys_symbol_underscore) if test x$ac_cv_sys_symbol_underscore = xyes; then AC_DEFINE(WITH_SYMBOL_UNDERSCORE,1, [Defined if compiled symbols have a leading underscore]) fi ]) ###################################################################### # Check whether mlock is broken (hpux 10.20 raises a SIGBUS if mlock # is not called from uid 0 (not tested whether uid 0 works) # For DECs Tru64 we have also to check whether mlock is in librt # mlock is there a macro using memlk() ###################################################################### dnl GNUPG_CHECK_MLOCK dnl define(GNUPG_CHECK_MLOCK, [ AC_CHECK_FUNCS(mlock) if test "$ac_cv_func_mlock" = "no"; then AC_CHECK_HEADERS(sys/mman.h) if test "$ac_cv_header_sys_mman_h" = "yes"; then # Add librt to LIBS: AC_CHECK_LIB(rt, memlk) AC_CACHE_CHECK([whether mlock is in sys/mman.h], gnupg_cv_mlock_is_in_sys_mman, [AC_TRY_LINK([ #include #ifdef HAVE_SYS_MMAN_H #include #endif ], [ int i; /* glibc defines this for functions which it implements * to always fail with ENOSYS. Some functions are actually * named something starting with __ and the normal name * is an alias. */ #if defined (__stub_mlock) || defined (__stub___mlock) choke me #else mlock(&i, 4); #endif ; return 0; ], gnupg_cv_mlock_is_in_sys_mman=yes, gnupg_cv_mlock_is_in_sys_mman=no)]) if test "$gnupg_cv_mlock_is_in_sys_mman" = "yes"; then AC_DEFINE(HAVE_MLOCK,1, [Defined if the system supports an mlock() call]) fi fi fi if test "$ac_cv_func_mlock" = "yes"; then AC_CHECK_FUNCS(sysconf getpagesize) AC_MSG_CHECKING(whether mlock is broken) AC_CACHE_VAL(gnupg_cv_have_broken_mlock, AC_TRY_RUN([ #include #include #include #include #include #include int main() { char *pool; int err; long int pgsize; #if defined(HAVE_SYSCONF) && defined(_SC_PAGESIZE) pgsize = sysconf (_SC_PAGESIZE); #elif defined (HAVE_GETPAGESIZE) pgsize = getpagesize(); #else pgsize = -1; #endif if (pgsize == -1) pgsize = 4096; pool = malloc( 4096 + pgsize ); if( !pool ) return 2; pool += (pgsize - ((long int)pool % pgsize)); err = mlock( pool, 4096 ); if( !err || errno == EPERM || errno == EAGAIN) return 0; /* okay */ return 1; /* hmmm */ } ], gnupg_cv_have_broken_mlock="no", gnupg_cv_have_broken_mlock="yes", gnupg_cv_have_broken_mlock="assume-no" ) ) if test "$gnupg_cv_have_broken_mlock" = "yes"; then AC_DEFINE(HAVE_BROKEN_MLOCK,1, [Defined if the mlock() call does not work]) AC_MSG_RESULT(yes) else if test "$gnupg_cv_have_broken_mlock" = "no"; then AC_MSG_RESULT(no) else AC_MSG_RESULT(assuming no) fi fi fi ]) # GNUPG_SYS_LIBTOOL_CYGWIN32 - find tools needed on cygwin32 AC_DEFUN([GNUPG_SYS_LIBTOOL_CYGWIN32], [AC_CHECK_TOOL(DLLTOOL, dlltool, false) AC_CHECK_TOOL(AS, as, false) ]) dnl LIST_MEMBER() -dnl Check wether an element ist contained in a list. Set `found' to +dnl Check whether an element ist contained in a list. Set `found' to dnl `1' if the element is found in the list, to `0' otherwise. AC_DEFUN([LIST_MEMBER], [ name=$1 list=$2 found=0 for n in $list; do if test "x$name" = "x$n"; then found=1 fi done ]) dnl Check for socklen_t: historically on BSD it is an int, and in dnl POSIX 1g it is a type of its own, but some platforms use different dnl types for the argument to getsockopt, getpeername, etc. So we dnl have to test to find something that will work. AC_DEFUN([TYPE_SOCKLEN_T], [ AC_CHECK_TYPE([socklen_t], ,[ AC_MSG_CHECKING([for socklen_t equivalent]) AC_CACHE_VAL([socklen_t_equiv], [ # Systems have either "struct sockaddr *" or # "void *" as the second argument to getpeername socklen_t_equiv= for arg2 in "struct sockaddr" void; do for t in int size_t unsigned long "unsigned long"; do AC_TRY_COMPILE([ #include #include int getpeername (int, $arg2 *, $t *); ],[ $t len; getpeername(0,0,&len); ],[ socklen_t_equiv="$t" break ]) done done if test "x$socklen_t_equiv" = x; then AC_MSG_ERROR([Cannot find a type to use in place of socklen_t]) fi ]) AC_MSG_RESULT($socklen_t_equiv) AC_DEFINE_UNQUOTED(socklen_t, $socklen_t_equiv, [type to use in place of socklen_t if not defined])], [#include #include ]) ]) # GNUPG_PTH_VERSION_CHECK(REQUIRED) # # If the version is sufficient, HAVE_PTH will be set to yes. # # Taken form the m4 macros which come with Pth AC_DEFUN([GNUPG_PTH_VERSION_CHECK], [ _pth_version=`$PTH_CONFIG --version | awk 'NR==1 {print [$]3}'` _req_version="ifelse([$1],,1.2.0,$1)" AC_MSG_CHECKING(for PTH - version >= $_req_version) for _var in _pth_version _req_version; do eval "_val=\"\$${_var}\"" _major=`echo $_val | sed 's/\([[0-9]]*\)\.\([[0-9]]*\)\([[ab.]]\)\([[0-9]]*\)/\1/'` _minor=`echo $_val | sed 's/\([[0-9]]*\)\.\([[0-9]]*\)\([[ab.]]\)\([[0-9]]*\)/\2/'` _rtype=`echo $_val | sed 's/\([[0-9]]*\)\.\([[0-9]]*\)\([[ab.]]\)\([[0-9]]*\)/\3/'` _micro=`echo $_val | sed 's/\([[0-9]]*\)\.\([[0-9]]*\)\([[ab.]]\)\([[0-9]]*\)/\4/'` case $_rtype in "a" ) _rtype=0 ;; "b" ) _rtype=1 ;; "." ) _rtype=2 ;; esac _hex=`echo dummy | awk '{ printf("%d%02d%1d%02d", major, minor, rtype, micro); }' \ "major=$_major" "minor=$_minor" "rtype=$_rtype" "micro=$_micro"` eval "${_var}_hex=\"\$_hex\"" done have_pth=no if test ".$_pth_version_hex" != .; then if test ".$_req_version_hex" != .; then if test $_pth_version_hex -ge $_req_version_hex; then have_pth=yes fi fi fi if test $have_pth = yes; then AC_MSG_RESULT(yes) AC_MSG_CHECKING([whether PTH installation is sane]) AC_CACHE_VAL(gnupg_cv_pth_is_sane,[ _gnupg_pth_save_cflags=$CFLAGS _gnupg_pth_save_ldflags=$LDFLAGS _gnupg_pth_save_libs=$LIBS CFLAGS="$CFLAGS `$PTH_CONFIG --cflags`" LDFLAGS="$LDFLAGS `$PTH_CONFIG --ldflags`" LIBS="$LIBS `$PTH_CONFIG --libs`" AC_LINK_IFELSE([AC_LANG_PROGRAM([#include ], [[ pth_init ();]])], gnupg_cv_pth_is_sane=yes, gnupg_cv_pth_is_sane=no) CFLAGS=$_gnupg_pth_save_cflags LDFLAGS=$_gnupg_pth_save_ldflags LIBS=$_gnupg_pth_save_libs ]) if test $gnupg_cv_pth_is_sane != yes; then have_pth=no fi AC_MSG_RESULT($gnupg_cv_pth_is_sane) else AC_MSG_RESULT(no) fi ]) diff --git a/build-aux/texinfo.tex b/build-aux/texinfo.tex index a1818982..5a17f979 100644 --- a/build-aux/texinfo.tex +++ b/build-aux/texinfo.tex @@ -1,8638 +1,8638 @@ % texinfo.tex -- TeX macros to handle Texinfo files. % % Load plain if necessary, i.e., if running under initex. \expandafter\ifx\csname fmtname\endcsname\relax\input plain\fi % \def\texinfoversion{2007-05-03.09} % % Copyright (C) 1985, 1986, 1988, 1990, 1991, 1992, 1993, 1994, 1995, % 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, % 2007 Free Software Foundation, Inc. % % This texinfo.tex file 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 3, or (at % your option) any later version. % % This texinfo.tex file 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 texinfo.tex file; see the file COPYING. If not, % see . % % As a special exception, when this file is read by TeX when processing % a Texinfo source document, you may use the result without % restriction. (This has been our intent since Texinfo was invented.) % % Please try the latest version of texinfo.tex before submitting bug % reports; you can get the latest version from: % http://www.gnu.org/software/texinfo/ (the Texinfo home page), or % ftp://tug.org/tex/texinfo.tex % (and all CTAN mirrors, see http://www.ctan.org). % The texinfo.tex in any given distribution could well be out % of date, so if that's what you're using, please check. % % Send bug reports to bug-texinfo@gnu.org. Please include including a % complete document in each bug report with which we can reproduce the % problem. Patches are, of course, greatly appreciated. % % To process a Texinfo manual with TeX, it's most reliable to use the % texi2dvi shell script that comes with the distribution. For a simple % manual foo.texi, however, you can get away with this: % tex foo.texi % texindex foo.?? % tex foo.texi % tex foo.texi % dvips foo.dvi -o # or whatever; this makes foo.ps. % The extra TeX runs get the cross-reference information correct. % Sometimes one run after texindex suffices, and sometimes you need more % than two; texi2dvi does it as many times as necessary. % % It is possible to adapt texinfo.tex for other languages, to some % extent. You can get the existing language-specific files from the % full Texinfo distribution. % % The GNU Texinfo home page is http://www.gnu.org/software/texinfo. \message{Loading texinfo [version \texinfoversion]:} % If in a .fmt file, print the version number % and turn on active characters that we couldn't do earlier because % they might have appeared in the input file name. \everyjob{\message{[Texinfo version \texinfoversion]}% \catcode`+=\active \catcode`\_=\active} \chardef\other=12 % We never want plain's \outer definition of \+ in Texinfo. % For @tex, we can use \tabalign. \let\+ = \relax % Save some plain tex macros whose names we will redefine. \let\ptexb=\b \let\ptexbullet=\bullet \let\ptexc=\c \let\ptexcomma=\, \let\ptexdot=\. \let\ptexdots=\dots \let\ptexend=\end \let\ptexequiv=\equiv \let\ptexexclam=\! \let\ptexfootnote=\footnote \let\ptexgtr=> \let\ptexhat=^ \let\ptexi=\i \let\ptexindent=\indent \let\ptexinsert=\insert \let\ptexlbrace=\{ \let\ptexless=< \let\ptexnewwrite\newwrite \let\ptexnoindent=\noindent \let\ptexplus=+ \let\ptexrbrace=\} \let\ptexslash=\/ \let\ptexstar=\* \let\ptext=\t % If this character appears in an error message or help string, it % starts a new line in the output. \newlinechar = `^^J % Use TeX 3.0's \inputlineno to get the line number, for better error % messages, but if we're using an old version of TeX, don't do anything. % \ifx\inputlineno\thisisundefined \let\linenumber = \empty % Pre-3.0. \else \def\linenumber{l.\the\inputlineno:\space} \fi % Set up fixed words for English if not already set. \ifx\putwordAppendix\undefined \gdef\putwordAppendix{Appendix}\fi \ifx\putwordChapter\undefined \gdef\putwordChapter{Chapter}\fi \ifx\putwordfile\undefined \gdef\putwordfile{file}\fi \ifx\putwordin\undefined \gdef\putwordin{in}\fi \ifx\putwordIndexIsEmpty\undefined \gdef\putwordIndexIsEmpty{(Index is empty)}\fi \ifx\putwordIndexNonexistent\undefined \gdef\putwordIndexNonexistent{(Index is nonexistent)}\fi \ifx\putwordInfo\undefined \gdef\putwordInfo{Info}\fi \ifx\putwordInstanceVariableof\undefined \gdef\putwordInstanceVariableof{Instance Variable of}\fi \ifx\putwordMethodon\undefined \gdef\putwordMethodon{Method on}\fi \ifx\putwordNoTitle\undefined \gdef\putwordNoTitle{No Title}\fi \ifx\putwordof\undefined \gdef\putwordof{of}\fi \ifx\putwordon\undefined \gdef\putwordon{on}\fi \ifx\putwordpage\undefined \gdef\putwordpage{page}\fi \ifx\putwordsection\undefined \gdef\putwordsection{section}\fi \ifx\putwordSection\undefined \gdef\putwordSection{Section}\fi \ifx\putwordsee\undefined \gdef\putwordsee{see}\fi \ifx\putwordSee\undefined \gdef\putwordSee{See}\fi \ifx\putwordShortTOC\undefined \gdef\putwordShortTOC{Short Contents}\fi \ifx\putwordTOC\undefined \gdef\putwordTOC{Table of Contents}\fi % \ifx\putwordMJan\undefined \gdef\putwordMJan{January}\fi \ifx\putwordMFeb\undefined \gdef\putwordMFeb{February}\fi \ifx\putwordMMar\undefined \gdef\putwordMMar{March}\fi \ifx\putwordMApr\undefined \gdef\putwordMApr{April}\fi \ifx\putwordMMay\undefined \gdef\putwordMMay{May}\fi \ifx\putwordMJun\undefined \gdef\putwordMJun{June}\fi \ifx\putwordMJul\undefined \gdef\putwordMJul{July}\fi \ifx\putwordMAug\undefined \gdef\putwordMAug{August}\fi \ifx\putwordMSep\undefined \gdef\putwordMSep{September}\fi \ifx\putwordMOct\undefined \gdef\putwordMOct{October}\fi \ifx\putwordMNov\undefined \gdef\putwordMNov{November}\fi \ifx\putwordMDec\undefined \gdef\putwordMDec{December}\fi % \ifx\putwordDefmac\undefined \gdef\putwordDefmac{Macro}\fi \ifx\putwordDefspec\undefined \gdef\putwordDefspec{Special Form}\fi \ifx\putwordDefvar\undefined \gdef\putwordDefvar{Variable}\fi \ifx\putwordDefopt\undefined \gdef\putwordDefopt{User Option}\fi \ifx\putwordDeffunc\undefined \gdef\putwordDeffunc{Function}\fi % Since the category of space is not known, we have to be careful. \chardef\spacecat = 10 \def\spaceisspace{\catcode`\ =\spacecat} % sometimes characters are active, so we need control sequences. \chardef\colonChar = `\: \chardef\commaChar = `\, \chardef\dashChar = `\- \chardef\dotChar = `\. \chardef\exclamChar= `\! \chardef\lquoteChar= `\` \chardef\questChar = `\? \chardef\rquoteChar= `\' \chardef\semiChar = `\; \chardef\underChar = `\_ % Ignore a token. % \def\gobble#1{} % The following is used inside several \edef's. \def\makecsname#1{\expandafter\noexpand\csname#1\endcsname} % Hyphenation fixes. \hyphenation{ Flor-i-da Ghost-script Ghost-view Mac-OS Post-Script ap-pen-dix bit-map bit-maps data-base data-bases eshell fall-ing half-way long-est man-u-script man-u-scripts mini-buf-fer mini-buf-fers over-view par-a-digm par-a-digms rath-er rec-tan-gu-lar ro-bot-ics se-vere-ly set-up spa-ces spell-ing spell-ings stand-alone strong-est time-stamp time-stamps which-ever white-space wide-spread wrap-around } % Margin to add to right of even pages, to left of odd pages. \newdimen\bindingoffset \newdimen\normaloffset \newdimen\pagewidth \newdimen\pageheight % For a final copy, take out the rectangles % that mark overfull boxes (in case you have decided % that the text looks ok even though it passes the margin). % \def\finalout{\overfullrule=0pt} % @| inserts a changebar to the left of the current line. It should % surround any changed text. This approach does *not* work if the % change spans more than two lines of output. To handle that, we would % have adopt a much more difficult approach (putting marks into the main % vertical list for the beginning and end of each change). % \def\|{% % \vadjust can only be used in horizontal mode. \leavevmode % % Append this vertical mode material after the current line in the output. \vadjust{% % We want to insert a rule with the height and depth of the current % leading; that is exactly what \strutbox is supposed to record. \vskip-\baselineskip % % \vadjust-items are inserted at the left edge of the type. So % the \llap here moves out into the left-hand margin. \llap{% % % For a thicker or thinner bar, change the `1pt'. \vrule height\baselineskip width1pt % % This is the space between the bar and the text. \hskip 12pt }% }% } % Sometimes it is convenient to have everything in the transcript file % and nothing on the terminal. We don't just call \tracingall here, % since that produces some useless output on the terminal. We also make % some effort to order the tracing commands to reduce output in the log % file; cf. trace.sty in LaTeX. % \def\gloggingall{\begingroup \globaldefs = 1 \loggingall \endgroup}% \def\loggingall{% \tracingstats2 \tracingpages1 \tracinglostchars2 % 2 gives us more in etex \tracingparagraphs1 \tracingoutput1 \tracingmacros2 \tracingrestores1 \showboxbreadth\maxdimen \showboxdepth\maxdimen \ifx\eTeXversion\undefined\else % etex gives us more logging \tracingscantokens1 \tracingifs1 \tracinggroups1 \tracingnesting2 \tracingassigns1 \fi \tracingcommands3 % 3 gives us more in etex \errorcontextlines16 }% % add check for \lastpenalty to plain's definitions. If the last thing % we did was a \nobreak, we don't want to insert more space. % \def\smallbreak{\ifnum\lastpenalty<10000\par\ifdim\lastskip<\smallskipamount \removelastskip\penalty-50\smallskip\fi\fi} \def\medbreak{\ifnum\lastpenalty<10000\par\ifdim\lastskip<\medskipamount \removelastskip\penalty-100\medskip\fi\fi} \def\bigbreak{\ifnum\lastpenalty<10000\par\ifdim\lastskip<\bigskipamount \removelastskip\penalty-200\bigskip\fi\fi} % For @cropmarks command. % Do @cropmarks to get crop marks. % \newif\ifcropmarks \let\cropmarks = \cropmarkstrue % % Dimensions to add cropmarks at corners. % Added by P. A. MacKay, 12 Nov. 1986 % \newdimen\outerhsize \newdimen\outervsize % set by the paper size routines \newdimen\cornerlong \cornerlong=1pc \newdimen\cornerthick \cornerthick=.3pt \newdimen\topandbottommargin \topandbottommargin=.75in % Main output routine. \chardef\PAGE = 255 \output = {\onepageout{\pagecontents\PAGE}} \newbox\headlinebox \newbox\footlinebox % \onepageout takes a vbox as an argument. Note that \pagecontents % does insertions, but you have to call it yourself. \def\onepageout#1{% \ifcropmarks \hoffset=0pt \else \hoffset=\normaloffset \fi % \ifodd\pageno \advance\hoffset by \bindingoffset \else \advance\hoffset by -\bindingoffset\fi % % Do this outside of the \shipout so @code etc. will be expanded in % the headline as they should be, not taken literally (outputting ''code). \setbox\headlinebox = \vbox{\let\hsize=\pagewidth \makeheadline}% \setbox\footlinebox = \vbox{\let\hsize=\pagewidth \makefootline}% % {% % Have to do this stuff outside the \shipout because we want it to % take effect in \write's, yet the group defined by the \vbox ends % before the \shipout runs. % \indexdummies % don't expand commands in the output. \normalturnoffactive % \ in index entries must not stay \, e.g., if % the page break happens to be in the middle of an example. % We don't want .vr (or whatever) entries like this: % \entry{{\tt \indexbackslash }acronym}{32}{\code {\acronym}} % "\acronym" won't work when it's read back in; % it needs to be % {\code {{\tt \backslashcurfont }acronym} \shipout\vbox{% % Do this early so pdf references go to the beginning of the page. \ifpdfmakepagedest \pdfdest name{\the\pageno} xyz\fi % \ifcropmarks \vbox to \outervsize\bgroup \hsize = \outerhsize \vskip-\topandbottommargin \vtop to0pt{% \line{\ewtop\hfil\ewtop}% \nointerlineskip \line{% \vbox{\moveleft\cornerthick\nstop}% \hfill \vbox{\moveright\cornerthick\nstop}% }% \vss}% \vskip\topandbottommargin \line\bgroup \hfil % center the page within the outer (page) hsize. \ifodd\pageno\hskip\bindingoffset\fi \vbox\bgroup \fi % \unvbox\headlinebox \pagebody{#1}% \ifdim\ht\footlinebox > 0pt % Only leave this space if the footline is nonempty. % (We lessened \vsize for it in \oddfootingyyy.) % The \baselineskip=24pt in plain's \makefootline has no effect. \vskip 24pt \unvbox\footlinebox \fi % \ifcropmarks \egroup % end of \vbox\bgroup \hfil\egroup % end of (centering) \line\bgroup \vskip\topandbottommargin plus1fill minus1fill \boxmaxdepth = \cornerthick \vbox to0pt{\vss \line{% \vbox{\moveleft\cornerthick\nsbot}% \hfill \vbox{\moveright\cornerthick\nsbot}% }% \nointerlineskip \line{\ewbot\hfil\ewbot}% }% \egroup % \vbox from first cropmarks clause \fi }% end of \shipout\vbox }% end of group with \indexdummies \advancepageno \ifnum\outputpenalty>-20000 \else\dosupereject\fi } \newinsert\margin \dimen\margin=\maxdimen \def\pagebody#1{\vbox to\pageheight{\boxmaxdepth=\maxdepth #1}} {\catcode`\@ =11 \gdef\pagecontents#1{\ifvoid\topins\else\unvbox\topins\fi % marginal hacks, juha@viisa.uucp (Juha Takala) \ifvoid\margin\else % marginal info is present \rlap{\kern\hsize\vbox to\z@{\kern1pt\box\margin \vss}}\fi \dimen@=\dp#1 \unvbox#1 \ifvoid\footins\else\vskip\skip\footins\footnoterule \unvbox\footins\fi \ifr@ggedbottom \kern-\dimen@ \vfil \fi} } % Here are the rules for the cropmarks. Note that they are % offset so that the space between them is truly \outerhsize or \outervsize % (P. A. MacKay, 12 November, 1986) % \def\ewtop{\vrule height\cornerthick depth0pt width\cornerlong} \def\nstop{\vbox {\hrule height\cornerthick depth\cornerlong width\cornerthick}} \def\ewbot{\vrule height0pt depth\cornerthick width\cornerlong} \def\nsbot{\vbox {\hrule height\cornerlong depth\cornerthick width\cornerthick}} % Parse an argument, then pass it to #1. The argument is the rest of % the input line (except we remove a trailing comment). #1 should be a % macro which expects an ordinary undelimited TeX argument. % \def\parsearg{\parseargusing{}} \def\parseargusing#1#2{% \def\argtorun{#2}% \begingroup \obeylines \spaceisspace #1% \parseargline\empty% Insert the \empty token, see \finishparsearg below. } {\obeylines % \gdef\parseargline#1^^M{% \endgroup % End of the group started in \parsearg. \argremovecomment #1\comment\ArgTerm% }% } % First remove any @comment, then any @c comment. \def\argremovecomment#1\comment#2\ArgTerm{\argremovec #1\c\ArgTerm} \def\argremovec#1\c#2\ArgTerm{\argcheckspaces#1\^^M\ArgTerm} -% Each occurence of `\^^M' or `\^^M' is replaced by a single space. +% Each occurrence of `\^^M' or `\^^M' is replaced by a single space. % % \argremovec might leave us with trailing space, e.g., % @end itemize @c foo % This space token undergoes the same procedure and is eventually removed % by \finishparsearg. % \def\argcheckspaces#1\^^M{\argcheckspacesX#1\^^M \^^M} \def\argcheckspacesX#1 \^^M{\argcheckspacesY#1\^^M} \def\argcheckspacesY#1\^^M#2\^^M#3\ArgTerm{% \def\temp{#3}% \ifx\temp\empty % Do not use \next, perhaps the caller of \parsearg uses it; reuse \temp: \let\temp\finishparsearg \else \let\temp\argcheckspaces \fi % Put the space token in: \temp#1 #3\ArgTerm } % If a _delimited_ argument is enclosed in braces, they get stripped; so % to get _exactly_ the rest of the line, we had to prevent such situation. % We prepended an \empty token at the very beginning and we expand it now, % just before passing the control to \argtorun. -% (Similarily, we have to think about #3 of \argcheckspacesY above: it is +% (Similarly, we have to think about #3 of \argcheckspacesY above: it is % either the null string, or it ends with \^^M---thus there is no danger % that a pair of braces would be stripped. % % But first, we have to remove the trailing space token. % \def\finishparsearg#1 \ArgTerm{\expandafter\argtorun\expandafter{#1}} % \parseargdef\foo{...} % is roughly equivalent to % \def\foo{\parsearg\Xfoo} % \def\Xfoo#1{...} % % Actually, I use \csname\string\foo\endcsname, ie. \\foo, as it is my % favourite TeX trick. --kasal, 16nov03 \def\parseargdef#1{% \expandafter \doparseargdef \csname\string#1\endcsname #1% } \def\doparseargdef#1#2{% \def#2{\parsearg#1}% \def#1##1% } % Several utility definitions with active space: { \obeyspaces \gdef\obeyedspace{ } % Make each space character in the input produce a normal interword % space in the output. Don't allow a line break at this space, as this % is used only in environments like @example, where each line of input % should produce a line of output anyway. % \gdef\sepspaces{\obeyspaces\let =\tie} % If an index command is used in an @example environment, any spaces % therein should become regular spaces in the raw index file, not the % expansion of \tie (\leavevmode \penalty \@M \ ). \gdef\unsepspaces{\let =\space} } \def\flushcr{\ifx\par\lisppar \def\next##1{}\else \let\next=\relax \fi \next} % Define the framework for environments in texinfo.tex. It's used like this: % % \envdef\foo{...} % \def\Efoo{...} % % It's the responsibility of \envdef to insert \begingroup before the % actual body; @end closes the group after calling \Efoo. \envdef also % defines \thisenv, so the current environment is known; @end checks % whether the environment name matches. The \checkenv macro can also be % used to check whether the current environment is the one expected. % % Non-false conditionals (@iftex, @ifset) don't fit into this, so they -% are not treated as enviroments; they don't open a group. (The +% are not treated as environments; they don't open a group. (The % implementation of @end takes care not to call \endgroup in this % special case.) % At runtime, environments start with this: \def\startenvironment#1{\begingroup\def\thisenv{#1}} % initialize \let\thisenv\empty % ... but they get defined via ``\envdef\foo{...}'': \long\def\envdef#1#2{\def#1{\startenvironment#1#2}} \def\envparseargdef#1#2{\parseargdef#1{\startenvironment#1#2}} % Check whether we're in the right environment: \def\checkenv#1{% \def\temp{#1}% \ifx\thisenv\temp \else \badenverr \fi } -% Evironment mismatch, #1 expected: +% Environment mismatch, #1 expected: \def\badenverr{% \errhelp = \EMsimple \errmessage{This command can appear only \inenvironment\temp, not \inenvironment\thisenv}% } \def\inenvironment#1{% \ifx#1\empty out of any environment% \else in environment \expandafter\string#1% \fi } % @end foo executes the definition of \Efoo. % But first, it executes a specialized version of \checkenv % \parseargdef\end{% \if 1\csname iscond.#1\endcsname \else % The general wording of \badenverr may not be ideal, but... --kasal, 06nov03 \expandafter\checkenv\csname#1\endcsname \csname E#1\endcsname \endgroup \fi } \newhelp\EMsimple{Press RETURN to continue.} %% Simple single-character @ commands % @@ prints an @ % Kludge this until the fonts are right (grr). \def\@{{\tt\char64}} % This is turned off because it was never documented % and you can use @w{...} around a quote to suppress ligatures. %% Define @` and @' to be the same as ` and ' %% but suppressing ligatures. %\def\`{{`}} %\def\'{{'}} % Used to generate quoted braces. \def\mylbrace {{\tt\char123}} \def\myrbrace {{\tt\char125}} \let\{=\mylbrace \let\}=\myrbrace \begingroup % Definitions to produce \{ and \} commands for indices, % and @{ and @} for the aux/toc files. \catcode`\{ = \other \catcode`\} = \other \catcode`\[ = 1 \catcode`\] = 2 \catcode`\! = 0 \catcode`\\ = \other !gdef!lbracecmd[\{]% !gdef!rbracecmd[\}]% !gdef!lbraceatcmd[@{]% !gdef!rbraceatcmd[@}]% !endgroup % @comma{} to avoid , parsing problems. \let\comma = , % Accents: @, @dotaccent @ringaccent @ubaraccent @udotaccent % Others are defined by plain TeX: @` @' @" @^ @~ @= @u @v @H. \let\, = \c \let\dotaccent = \. \def\ringaccent#1{{\accent23 #1}} \let\tieaccent = \t \let\ubaraccent = \b \let\udotaccent = \d % Other special characters: @questiondown @exclamdown @ordf @ordm % Plain TeX defines: @AA @AE @O @OE @L (plus lowercase versions) @ss. \def\questiondown{?`} \def\exclamdown{!`} \def\ordf{\leavevmode\raise1ex\hbox{\selectfonts\lllsize \underbar{a}}} \def\ordm{\leavevmode\raise1ex\hbox{\selectfonts\lllsize \underbar{o}}} % Dotless i and dotless j, used for accents. \def\imacro{i} \def\jmacro{j} \def\dotless#1{% \def\temp{#1}% \ifx\temp\imacro \ptexi \else\ifx\temp\jmacro \j \else \errmessage{@dotless can be used only with i or j}% \fi\fi } % The \TeX{} logo, as in plain, but resetting the spacing so that a % period following counts as ending a sentence. (Idea found in latex.) % \edef\TeX{\TeX \spacefactor=1000 } % @LaTeX{} logo. Not quite the same results as the definition in % latex.ltx, since we use a different font for the raised A; it's most % convenient for us to use an explicitly smaller font, rather than using % the \scriptstyle font (since we don't reset \scriptstyle and % \scriptscriptstyle). % \def\LaTeX{% L\kern-.36em {\setbox0=\hbox{T}% \vbox to \ht0{\hbox{\selectfonts\lllsize A}\vss}}% \kern-.15em \TeX } % Be sure we're in horizontal mode when doing a tie, since we make space % equivalent to this in @example-like environments. Otherwise, a space % at the beginning of a line will start with \penalty -- and % since \penalty is valid in vertical mode, we'd end up putting the % penalty on the vertical list instead of in the new paragraph. {\catcode`@ = 11 % Avoid using \@M directly, because that causes trouble % if the definition is written into an index file. \global\let\tiepenalty = \@M \gdef\tie{\leavevmode\penalty\tiepenalty\ } } % @: forces normal size whitespace following. \def\:{\spacefactor=1000 } % @* forces a line break. \def\*{\hfil\break\hbox{}\ignorespaces} % @/ allows a line break. \let\/=\allowbreak % @. is an end-of-sentence period. \def\.{.\spacefactor=\endofsentencespacefactor\space} % @! is an end-of-sentence bang. \def\!{!\spacefactor=\endofsentencespacefactor\space} % @? is an end-of-sentence query. \def\?{?\spacefactor=\endofsentencespacefactor\space} % @frenchspacing on|off says whether to put extra space after punctuation. % \def\onword{on} \def\offword{off} % \parseargdef\frenchspacing{% \def\temp{#1}% \ifx\temp\onword \plainfrenchspacing \else\ifx\temp\offword \plainnonfrenchspacing \else \errhelp = \EMsimple \errmessage{Unknown @frenchspacing option `\temp', must be on/off}% \fi\fi } % @w prevents a word break. Without the \leavevmode, @w at the % beginning of a paragraph, when TeX is still in vertical mode, would % produce a whole line of output instead of starting the paragraph. \def\w#1{\leavevmode\hbox{#1}} % @group ... @end group forces ... to be all on one page, by enclosing % it in a TeX vbox. We use \vtop instead of \vbox to construct the box % to keep its height that of a normal line. According to the rules for % \topskip (p.114 of the TeXbook), the glue inserted is % max (\topskip - \ht (first item), 0). If that height is large, % therefore, no glue is inserted, and the space between the headline and % the text is small, which looks bad. % % Another complication is that the group might be very large. This can % cause the glue on the previous page to be unduly stretched, because it % does not have much material. In this case, it's better to add an % explicit \vfill so that the extra space is at the bottom. The % threshold for doing this is if the group is more than \vfilllimit % percent of a page (\vfilllimit can be changed inside of @tex). % \newbox\groupbox \def\vfilllimit{0.7} % \envdef\group{% \ifnum\catcode`\^^M=\active \else \errhelp = \groupinvalidhelp \errmessage{@group invalid in context where filling is enabled}% \fi \startsavinginserts % \setbox\groupbox = \vtop\bgroup % Do @comment since we are called inside an environment such as % @example, where each end-of-line in the input causes an % end-of-line in the output. We don't want the end-of-line after % the `@group' to put extra space in the output. Since @group % should appear on a line by itself (according to the Texinfo % manual), we don't worry about eating any user text. \comment } % % The \vtop produces a box with normal height and large depth; thus, TeX puts % \baselineskip glue before it, and (when the next line of text is done) % \lineskip glue after it. Thus, space below is not quite equal to space % above. But it's pretty close. \def\Egroup{% % To get correct interline space between the last line of the group % and the first line afterwards, we have to propagate \prevdepth. \endgraf % Not \par, as it may have been set to \lisppar. \global\dimen1 = \prevdepth \egroup % End the \vtop. % \dimen0 is the vertical size of the group's box. \dimen0 = \ht\groupbox \advance\dimen0 by \dp\groupbox % \dimen2 is how much space is left on the page (more or less). \dimen2 = \pageheight \advance\dimen2 by -\pagetotal % if the group doesn't fit on the current page, and it's a big big % group, force a page break. \ifdim \dimen0 > \dimen2 \ifdim \pagetotal < \vfilllimit\pageheight \page \fi \fi \box\groupbox \prevdepth = \dimen1 \checkinserts } % % TeX puts in an \escapechar (i.e., `@') at the beginning of the help % message, so this ends up printing `@group can only ...'. % \newhelp\groupinvalidhelp{% group can only be used in environments such as @example,^^J% where each line of input produces a line of output.} % @need space-in-mils % forces a page break if there is not space-in-mils remaining. \newdimen\mil \mil=0.001in % Old definition--didn't work. %\parseargdef\need{\par % %% This method tries to make TeX break the page naturally %% if the depth of the box does not fit. %{\baselineskip=0pt% %\vtop to #1\mil{\vfil}\kern -#1\mil\nobreak %\prevdepth=-1000pt %}} \parseargdef\need{% % Ensure vertical mode, so we don't make a big box in the middle of a % paragraph. \par % % If the @need value is less than one line space, it's useless. \dimen0 = #1\mil \dimen2 = \ht\strutbox \advance\dimen2 by \dp\strutbox \ifdim\dimen0 > \dimen2 % % Do a \strut just to make the height of this box be normal, so the % normal leading is inserted relative to the preceding line. % And a page break here is fine. \vtop to #1\mil{\strut\vfil}% % % TeX does not even consider page breaks if a penalty added to the % main vertical list is 10000 or more. But in order to see if the % empty box we just added fits on the page, we must make it consider % page breaks. On the other hand, we don't want to actually break the % page after the empty box. So we use a penalty of 9999. % % There is an extremely small chance that TeX will actually break the % page at this \penalty, if there are no other feasible breakpoints in % sight. (If the user is using lots of big @group commands, which % almost-but-not-quite fill up a page, TeX will have a hard time doing % good page breaking, for example.) However, I could not construct an % example where a page broke at this \penalty; if it happens in a real % document, then we can reconsider our strategy. \penalty9999 % % Back up by the size of the box, whether we did a page break or not. \kern -#1\mil % % Do not allow a page break right after this kern. \nobreak \fi } % @br forces paragraph break (and is undocumented). \let\br = \par % @page forces the start of a new page. % \def\page{\par\vfill\supereject} % @exdent text.... % outputs text on separate line in roman font, starting at standard page margin % This records the amount of indent in the innermost environment. % That's how much \exdent should take out. \newskip\exdentamount % This defn is used inside fill environments such as @defun. \parseargdef\exdent{\hfil\break\hbox{\kern -\exdentamount{\rm#1}}\hfil\break} % This defn is used inside nofill environments such as @example. \parseargdef\nofillexdent{{\advance \leftskip by -\exdentamount \leftline{\hskip\leftskip{\rm#1}}}} % @inmargin{WHICH}{TEXT} puts TEXT in the WHICH margin next to the current % paragraph. For more general purposes, use the \margin insertion % class. WHICH is `l' or `r'. % \newskip\inmarginspacing \inmarginspacing=1cm \def\strutdepth{\dp\strutbox} % \def\doinmargin#1#2{\strut\vadjust{% \nobreak \kern-\strutdepth \vtop to \strutdepth{% \baselineskip=\strutdepth \vss % if you have multiple lines of stuff to put here, you'll need to % make the vbox yourself of the appropriate size. \ifx#1l% \llap{\ignorespaces #2\hskip\inmarginspacing}% \else \rlap{\hskip\hsize \hskip\inmarginspacing \ignorespaces #2}% \fi \null }% }} \def\inleftmargin{\doinmargin l} \def\inrightmargin{\doinmargin r} % % @inmargin{TEXT [, RIGHT-TEXT]} % (if RIGHT-TEXT is given, use TEXT for left page, RIGHT-TEXT for right; % else use TEXT for both). % \def\inmargin#1{\parseinmargin #1,,\finish} \def\parseinmargin#1,#2,#3\finish{% not perfect, but better than nothing. \setbox0 = \hbox{\ignorespaces #2}% \ifdim\wd0 > 0pt \def\lefttext{#1}% have both texts \def\righttext{#2}% \else \def\lefttext{#1}% have only one text \def\righttext{#1}% \fi % \ifodd\pageno \def\temp{\inrightmargin\righttext}% odd page -> outside is right margin \else \def\temp{\inleftmargin\lefttext}% \fi \temp } % @include file insert text of that file as input. % \def\include{\parseargusing\filenamecatcodes\includezzz} \def\includezzz#1{% \pushthisfilestack \def\thisfile{#1}% {% \makevalueexpandable \def\temp{\input #1 }% \expandafter }\temp \popthisfilestack } \def\filenamecatcodes{% \catcode`\\=\other \catcode`~=\other \catcode`^=\other \catcode`_=\other \catcode`|=\other \catcode`<=\other \catcode`>=\other \catcode`+=\other \catcode`-=\other } \def\pushthisfilestack{% \expandafter\pushthisfilestackX\popthisfilestack\StackTerm } \def\pushthisfilestackX{% \expandafter\pushthisfilestackY\thisfile\StackTerm } \def\pushthisfilestackY #1\StackTerm #2\StackTerm {% \gdef\popthisfilestack{\gdef\thisfile{#1}\gdef\popthisfilestack{#2}}% } \def\popthisfilestack{\errthisfilestackempty} \def\errthisfilestackempty{\errmessage{Internal error: the stack of filenames is empty.}} \def\thisfile{} % @center line % outputs that line, centered. % \parseargdef\center{% \ifhmode \let\next\centerH \else \let\next\centerV \fi \next{\hfil \ignorespaces#1\unskip \hfil}% } \def\centerH#1{% {% \hfil\break \advance\hsize by -\leftskip \advance\hsize by -\rightskip \line{#1}% \break }% } \def\centerV#1{\line{\kern\leftskip #1\kern\rightskip}} % @sp n outputs n lines of vertical space \parseargdef\sp{\vskip #1\baselineskip} % @comment ...line which is ignored... % @c is the same as @comment % @ignore ... @end ignore is another way to write a comment \def\comment{\begingroup \catcode`\^^M=\other% \catcode`\@=\other \catcode`\{=\other \catcode`\}=\other% \commentxxx} {\catcode`\^^M=\other \gdef\commentxxx#1^^M{\endgroup}} \let\c=\comment % @paragraphindent NCHARS % We'll use ems for NCHARS, close enough. % NCHARS can also be the word `asis' or `none'. % We cannot feasibly implement @paragraphindent asis, though. % \def\asisword{asis} % no translation, these are keywords \def\noneword{none} % \parseargdef\paragraphindent{% \def\temp{#1}% \ifx\temp\asisword \else \ifx\temp\noneword \defaultparindent = 0pt \else \defaultparindent = #1em \fi \fi \parindent = \defaultparindent } % @exampleindent NCHARS % We'll use ems for NCHARS like @paragraphindent. % It seems @exampleindent asis isn't necessary, but % I preserve it to make it similar to @paragraphindent. \parseargdef\exampleindent{% \def\temp{#1}% \ifx\temp\asisword \else \ifx\temp\noneword \lispnarrowing = 0pt \else \lispnarrowing = #1em \fi \fi } % @firstparagraphindent WORD % If WORD is `none', then suppress indentation of the first paragraph % after a section heading. If WORD is `insert', then do indent at such % paragraphs. % % The paragraph indentation is suppressed or not by calling % \suppressfirstparagraphindent, which the sectioning commands do. % We switch the definition of this back and forth according to WORD. % By default, we suppress indentation. % \def\suppressfirstparagraphindent{\dosuppressfirstparagraphindent} \def\insertword{insert} % \parseargdef\firstparagraphindent{% \def\temp{#1}% \ifx\temp\noneword \let\suppressfirstparagraphindent = \dosuppressfirstparagraphindent \else\ifx\temp\insertword \let\suppressfirstparagraphindent = \relax \else \errhelp = \EMsimple \errmessage{Unknown @firstparagraphindent option `\temp'}% \fi\fi } % Here is how we actually suppress indentation. Redefine \everypar to % \kern backwards by \parindent, and then reset itself to empty. % % We also make \indent itself not actually do anything until the next % paragraph. % \gdef\dosuppressfirstparagraphindent{% \gdef\indent{% \restorefirstparagraphindent \indent }% \gdef\noindent{% \restorefirstparagraphindent \noindent }% \global\everypar = {% \kern -\parindent \restorefirstparagraphindent }% } \gdef\restorefirstparagraphindent{% \global \let \indent = \ptexindent \global \let \noindent = \ptexnoindent \global \everypar = {}% } % @asis just yields its argument. Used with @table, for example. % \def\asis#1{#1} % @math outputs its argument in math mode. % % One complication: _ usually means subscripts, but it could also mean % an actual _ character, as in @math{@var{some_variable} + 1}. So make % _ active, and distinguish by seeing if the current family is \slfam, % which is what @var uses. { \catcode`\_ = \active \gdef\mathunderscore{% \catcode`\_=\active \def_{\ifnum\fam=\slfam \_\else\sb\fi}% } } % Another complication: we want \\ (and @\) to output a \ character. % FYI, plain.tex uses \\ as a temporary control sequence (why?), but % this is not advertised and we don't care. Texinfo does not % otherwise define @\. % % The \mathchar is class=0=ordinary, family=7=ttfam, position=5C=\. \def\mathbackslash{\ifnum\fam=\ttfam \mathchar"075C \else\backslash \fi} % \def\math{% \tex \mathunderscore \let\\ = \mathbackslash \mathactive $\finishmath } \def\finishmath#1{#1$\endgroup} % Close the group opened by \tex. % Some active characters (such as <) are spaced differently in math. % We have to reset their definitions in case the @math was an argument % to a command which sets the catcodes (such as @item or @section). % { \catcode`^ = \active \catcode`< = \active \catcode`> = \active \catcode`+ = \active \gdef\mathactive{% \let^ = \ptexhat \let< = \ptexless \let> = \ptexgtr \let+ = \ptexplus } } % @bullet and @minus need the same treatment as @math, just above. \def\bullet{$\ptexbullet$} \def\minus{$-$} % @dots{} outputs an ellipsis using the current font. % We do .5em per period so that it has the same spacing in the cm % typewriter fonts as three actual period characters; on the other hand, % in other typewriter fonts three periods are wider than 1.5em. So do % whichever is larger. % \def\dots{% \leavevmode \setbox0=\hbox{...}% get width of three periods \ifdim\wd0 > 1.5em \dimen0 = \wd0 \else \dimen0 = 1.5em \fi \hbox to \dimen0{% \hskip 0pt plus.25fil .\hskip 0pt plus1fil .\hskip 0pt plus1fil .\hskip 0pt plus.5fil }% } % @enddots{} is an end-of-sentence ellipsis. % \def\enddots{% \dots \spacefactor=\endofsentencespacefactor } % @comma{} is so commas can be inserted into text without messing up % Texinfo's parsing. % \let\comma = , % @refill is a no-op. \let\refill=\relax % If working on a large document in chapters, it is convenient to % be able to disable indexing, cross-referencing, and contents, for test runs. % This is done with @novalidate (before @setfilename). % \newif\iflinks \linkstrue % by default we want the aux files. \let\novalidate = \linksfalse % @setfilename is done at the beginning of every texinfo file. % So open here the files we need to have open while reading the input. % This makes it possible to make a .fmt file for texinfo. \def\setfilename{% \fixbackslash % Turn off hack to swallow `\input texinfo'. \iflinks \tryauxfile % Open the new aux file. TeX will close it automatically at exit. \immediate\openout\auxfile=\jobname.aux \fi % \openindices needs to do some work in any case. \openindices \let\setfilename=\comment % Ignore extra @setfilename cmds. % % If texinfo.cnf is present on the system, read it. % Useful for site-wide @afourpaper, etc. \openin 1 texinfo.cnf \ifeof 1 \else \input texinfo.cnf \fi \closein 1 % \comment % Ignore the actual filename. } % Called from \setfilename. % \def\openindices{% \newindex{cp}% \newcodeindex{fn}% \newcodeindex{vr}% \newcodeindex{tp}% \newcodeindex{ky}% \newcodeindex{pg}% } % @bye. \outer\def\bye{\pagealignmacro\tracingstats=1\ptexend} \message{pdf,} % adobe `portable' document format \newcount\tempnum \newcount\lnkcount \newtoks\filename \newcount\filenamelength \newcount\pgn \newtoks\toksA \newtoks\toksB \newtoks\toksC \newtoks\toksD \newbox\boxA \newcount\countA \newif\ifpdf \newif\ifpdfmakepagedest % when pdftex is run in dvi mode, \pdfoutput is defined (so \pdfoutput=1 % can be set). So we test for \relax and 0 as well as \undefined, % borrowed from ifpdf.sty. \ifx\pdfoutput\undefined \else \ifx\pdfoutput\relax \else \ifcase\pdfoutput \else \pdftrue \fi \fi \fi % PDF uses PostScript string constants for the names of xref targets, % for display in the outlines, and in other places. Thus, we have to % double any backslashes. Otherwise, a name like "\node" will be % interpreted as a newline (\n), followed by o, d, e. Not good. % http://www.ntg.nl/pipermail/ntg-pdftex/2004-July/000654.html % (and related messages, the final outcome is that it is up to the TeX % user to double the backslashes and otherwise make the string valid, so % that's what we do). % double active backslashes. % {\catcode`\@=0 \catcode`\\=\active @gdef@activebackslashdouble{% @catcode`@\=@active @let\=@doublebackslash} } % To handle parens, we must adopt a different approach, since parens are % not active characters. hyperref.dtx (which has the same problem as % us) handles it with this amazing macro to replace tokens, with minor % changes for Texinfo. It is included here under the GPL by permission % from the author, Heiko Oberdiek. % % #1 is the tokens to replace. % #2 is the replacement. % #3 is the control sequence with the string. % \def\HyPsdSubst#1#2#3{% \def\HyPsdReplace##1#1##2\END{% ##1% \ifx\\##2\\% \else #2% \HyReturnAfterFi{% \HyPsdReplace##2\END }% \fi }% \xdef#3{\expandafter\HyPsdReplace#3#1\END}% } \long\def\HyReturnAfterFi#1\fi{\fi#1} % #1 is a control sequence in which to do the replacements. \def\backslashparens#1{% \xdef#1{#1}% redefine it as its expansion; the definition is simply % \lastnode when called from \setref -> \pdfmkdest. \HyPsdSubst{(}{\realbackslash(}{#1}% \HyPsdSubst{)}{\realbackslash)}{#1}% } \newhelp\nopdfimagehelp{Texinfo supports .png, .jpg, .jpeg, and .pdf images with PDF output, and none of those formats could be found. (.eps cannot be supported due to the design of the PDF format; use regular TeX (DVI output) for that.)} \ifpdf \input pdfcolor \pdfcatalog{/PageMode /UseOutlines} % % #1 is image name, #2 width (might be empty/whitespace), #3 height (ditto). \def\dopdfimage#1#2#3{% \def\imagewidth{#2}\setbox0 = \hbox{\ignorespaces #2}% \def\imageheight{#3}\setbox2 = \hbox{\ignorespaces #3}% % % pdftex (and the PDF format) support .png, .jpg, .pdf (among % others). Let's try in that order. \let\pdfimgext=\empty \begingroup \openin 1 #1.png \ifeof 1 \openin 1 #1.jpg \ifeof 1 \openin 1 #1.jpeg \ifeof 1 \openin 1 #1.JPG \ifeof 1 \openin 1 #1.pdf \ifeof 1 \errhelp = \nopdfimagehelp \errmessage{Could not find image file #1 for pdf}% \else \gdef\pdfimgext{pdf}% \fi \else \gdef\pdfimgext{JPG}% \fi \else \gdef\pdfimgext{jpeg}% \fi \else \gdef\pdfimgext{jpg}% \fi \else \gdef\pdfimgext{png}% \fi \closein 1 \endgroup % % without \immediate, pdftex seg faults when the same image is % included twice. (Version 3.14159-pre-1.0-unofficial-20010704.) \ifnum\pdftexversion < 14 \immediate\pdfimage \else \immediate\pdfximage \fi \ifdim \wd0 >0pt width \imagewidth \fi \ifdim \wd2 >0pt height \imageheight \fi \ifnum\pdftexversion<13 #1.\pdfimgext \else {#1.\pdfimgext}% \fi \ifnum\pdftexversion < 14 \else \pdfrefximage \pdflastximage \fi} % \def\pdfmkdest#1{{% % We have to set dummies so commands such as @code, and characters % such as \, aren't expanded when present in a section title. \indexnofonts \turnoffactive \activebackslashdouble \makevalueexpandable \def\pdfdestname{#1}% \backslashparens\pdfdestname \safewhatsit{\pdfdest name{\pdfdestname} xyz}% }} % % used to mark target names; must be expandable. \def\pdfmkpgn#1{#1} % % by default, use a color that is dark enough to print on paper as % nearly black, but still distinguishable for online viewing. % (Defined in pdfcolor.tex.) \let\urlcolor = \BrickRed \let\linkcolor = \BrickRed \def\endlink{\Black\pdfendlink} % % Adding outlines to PDF; macros for calculating structure of outlines % come from Petr Olsak \def\expnumber#1{\expandafter\ifx\csname#1\endcsname\relax 0% \else \csname#1\endcsname \fi} \def\advancenumber#1{\tempnum=\expnumber{#1}\relax \advance\tempnum by 1 \expandafter\xdef\csname#1\endcsname{\the\tempnum}} % % #1 is the section text, which is what will be displayed in the % outline by the pdf viewer. #2 is the pdf expression for the number % of subentries (or empty, for subsubsections). #3 is the node text, % which might be empty if this toc entry had no corresponding node. % #4 is the page number % \def\dopdfoutline#1#2#3#4{% % Generate a link to the node text if that exists; else, use the % page number. We could generate a destination for the section % text in the case where a section has no node, but it doesn't % seem worth the trouble, since most documents are normally structured. \def\pdfoutlinedest{#3}% \ifx\pdfoutlinedest\empty \def\pdfoutlinedest{#4}% \else % Doubled backslashes in the name. {\activebackslashdouble \xdef\pdfoutlinedest{#3}% \backslashparens\pdfoutlinedest}% \fi % % Also double the backslashes in the display string. {\activebackslashdouble \xdef\pdfoutlinetext{#1}% \backslashparens\pdfoutlinetext}% % \pdfoutline goto name{\pdfmkpgn{\pdfoutlinedest}}#2{\pdfoutlinetext}% } % \def\pdfmakeoutlines{% \begingroup % Thanh's hack / proper braces in bookmarks \edef\mylbrace{\iftrue \string{\else}\fi}\let\{=\mylbrace \edef\myrbrace{\iffalse{\else\string}\fi}\let\}=\myrbrace % % Read toc silently, to get counts of subentries for \pdfoutline. \def\numchapentry##1##2##3##4{% \def\thischapnum{##2}% \def\thissecnum{0}% \def\thissubsecnum{0}% }% \def\numsecentry##1##2##3##4{% \advancenumber{chap\thischapnum}% \def\thissecnum{##2}% \def\thissubsecnum{0}% }% \def\numsubsecentry##1##2##3##4{% \advancenumber{sec\thissecnum}% \def\thissubsecnum{##2}% }% \def\numsubsubsecentry##1##2##3##4{% \advancenumber{subsec\thissubsecnum}% }% \def\thischapnum{0}% \def\thissecnum{0}% \def\thissubsecnum{0}% % % use \def rather than \let here because we redefine \chapentry et % al. a second time, below. \def\appentry{\numchapentry}% \def\appsecentry{\numsecentry}% \def\appsubsecentry{\numsubsecentry}% \def\appsubsubsecentry{\numsubsubsecentry}% \def\unnchapentry{\numchapentry}% \def\unnsecentry{\numsecentry}% \def\unnsubsecentry{\numsubsecentry}% \def\unnsubsubsecentry{\numsubsubsecentry}% \readdatafile{toc}% % % Read toc second time, this time actually producing the outlines. % The `-' means take the \expnumber as the absolute number of % subentries, which we calculated on our first read of the .toc above. % % We use the node names as the destinations. \def\numchapentry##1##2##3##4{% \dopdfoutline{##1}{count-\expnumber{chap##2}}{##3}{##4}}% \def\numsecentry##1##2##3##4{% \dopdfoutline{##1}{count-\expnumber{sec##2}}{##3}{##4}}% \def\numsubsecentry##1##2##3##4{% \dopdfoutline{##1}{count-\expnumber{subsec##2}}{##3}{##4}}% \def\numsubsubsecentry##1##2##3##4{% count is always zero \dopdfoutline{##1}{}{##3}{##4}}% % % PDF outlines are displayed using system fonts, instead of % document fonts. Therefore we cannot use special characters, % since the encoding is unknown. For example, the eogonek from % Latin 2 (0xea) gets translated to a | character. Info from % Staszek Wawrykiewicz, 19 Jan 2004 04:09:24 +0100. % % xx to do this right, we have to translate 8-bit characters to % their "best" equivalent, based on the @documentencoding. Right % now, I guess we'll just let the pdf reader have its way. \indexnofonts \setupdatafile \catcode`\\=\active \otherbackslash \input \jobname.toc \endgroup } % \def\skipspaces#1{\def\PP{#1}\def\D{|}% \ifx\PP\D\let\nextsp\relax \else\let\nextsp\skipspaces \ifx\p\space\else\addtokens{\filename}{\PP}% \advance\filenamelength by 1 \fi \fi \nextsp} \def\getfilename#1{\filenamelength=0\expandafter\skipspaces#1|\relax} \ifnum\pdftexversion < 14 \let \startlink \pdfannotlink \else \let \startlink \pdfstartlink \fi % make a live url in pdf output. \def\pdfurl#1{% \begingroup % it seems we really need yet another set of dummies; have not % tried to figure out what each command should do in the context % of @url. for now, just make @/ a no-op, that's the only one % people have actually reported a problem with. % \normalturnoffactive \def\@{@}% \let\/=\empty \makevalueexpandable \leavevmode\urlcolor \startlink attr{/Border [0 0 0]}% user{/Subtype /Link /A << /S /URI /URI (#1) >>}% \endgroup} \def\pdfgettoks#1.{\setbox\boxA=\hbox{\toksA={#1.}\toksB={}\maketoks}} \def\addtokens#1#2{\edef\addtoks{\noexpand#1={\the#1#2}}\addtoks} \def\adn#1{\addtokens{\toksC}{#1}\global\countA=1\let\next=\maketoks} \def\poptoks#1#2|ENDTOKS|{\let\first=#1\toksD={#1}\toksA={#2}} \def\maketoks{% \expandafter\poptoks\the\toksA|ENDTOKS|\relax \ifx\first0\adn0 \else\ifx\first1\adn1 \else\ifx\first2\adn2 \else\ifx\first3\adn3 \else\ifx\first4\adn4 \else\ifx\first5\adn5 \else\ifx\first6\adn6 \else\ifx\first7\adn7 \else\ifx\first8\adn8 \else\ifx\first9\adn9 \else \ifnum0=\countA\else\makelink\fi \ifx\first.\let\next=\done\else \let\next=\maketoks \addtokens{\toksB}{\the\toksD} \ifx\first,\addtokens{\toksB}{\space}\fi \fi \fi\fi\fi\fi\fi\fi\fi\fi\fi\fi \next} \def\makelink{\addtokens{\toksB}% {\noexpand\pdflink{\the\toksC}}\toksC={}\global\countA=0} \def\pdflink#1{% \startlink attr{/Border [0 0 0]} goto name{\pdfmkpgn{#1}} \linkcolor #1\endlink} \def\done{\edef\st{\global\noexpand\toksA={\the\toksB}}\st} \else \let\pdfmkdest = \gobble \let\pdfurl = \gobble \let\endlink = \relax \let\linkcolor = \relax \let\pdfmakeoutlines = \relax \fi % \ifx\pdfoutput \message{fonts,} % Change the current font style to #1, remembering it in \curfontstyle. % For now, we do not accumulate font styles: @b{@i{foo}} prints foo in % italics, not bold italics. % \def\setfontstyle#1{% \def\curfontstyle{#1}% not as a control sequence, because we are \edef'd. \csname ten#1\endcsname % change the current font } % Select #1 fonts with the current style. % \def\selectfonts#1{\csname #1fonts\endcsname \csname\curfontstyle\endcsname} \def\rm{\fam=0 \setfontstyle{rm}} \def\it{\fam=\itfam \setfontstyle{it}} \def\sl{\fam=\slfam \setfontstyle{sl}} \def\bf{\fam=\bffam \setfontstyle{bf}}\def\bfstylename{bf} \def\tt{\fam=\ttfam \setfontstyle{tt}} % Texinfo sort of supports the sans serif font style, which plain TeX does not. % So we set up a \sf. \newfam\sffam \def\sf{\fam=\sffam \setfontstyle{sf}} \let\li = \sf % Sometimes we call it \li, not \sf. % We don't need math for this font style. \def\ttsl{\setfontstyle{ttsl}} % Default leading. \newdimen\textleading \textleading = 13.2pt % Set the baselineskip to #1, and the lineskip and strut size % correspondingly. There is no deep meaning behind these magic numbers % used as factors; they just match (closely enough) what Knuth defined. % \def\lineskipfactor{.08333} \def\strutheightpercent{.70833} \def\strutdepthpercent {.29167} % \def\setleading#1{% \normalbaselineskip = #1\relax \normallineskip = \lineskipfactor\normalbaselineskip \normalbaselines \setbox\strutbox =\hbox{% \vrule width0pt height\strutheightpercent\baselineskip depth \strutdepthpercent \baselineskip }% } % % PDF CMaps. See also LaTeX's t1.cmap. % % \cmapOT1 \ifpdf \begingroup \catcode`\^^M=\active \def^^M{^^J}% Output line endings as the ^^J char. \catcode`\%=12 \immediate\pdfobj stream {%!PS-Adobe-3.0 Resource-CMap %%DocumentNeededResources: ProcSet (CIDInit) %%IncludeResource: ProcSet (CIDInit) %%BeginResource: CMap (TeX-OT1-0) %%Title: (TeX-OT1-0 TeX OT1 0) %%Version: 1.000 %%EndComments /CIDInit /ProcSet findresource begin 12 dict begin begincmap /CIDSystemInfo << /Registry (TeX) /Ordering (OT1) /Supplement 0 >> def /CMapName /TeX-OT1-0 def /CMapType 2 def 1 begincodespacerange <00> <7F> endcodespacerange 8 beginbfrange <00> <01> <0393> <09> <0A> <03A8> <23> <26> <0023> <28> <3B> <0028> <3F> <5B> <003F> <5D> <5E> <005D> <61> <7A> <0061> <7B> <7C> <2013> endbfrange 40 beginbfchar <02> <0398> <03> <039B> <04> <039E> <05> <03A0> <06> <03A3> <07> <03D2> <08> <03A6> <0B> <00660066> <0C> <00660069> <0D> <0066006C> <0E> <006600660069> <0F> <00660066006C> <10> <0131> <11> <0237> <12> <0060> <13> <00B4> <14> <02C7> <15> <02D8> <16> <00AF> <17> <02DA> <18> <00B8> <19> <00DF> <1A> <00E6> <1B> <0153> <1C> <00F8> <1D> <00C6> <1E> <0152> <1F> <00D8> <21> <0021> <22> <201D> <27> <2019> <3C> <00A1> <3D> <003D> <3E> <00BF> <5C> <201C> <5F> <02D9> <60> <2018> <7D> <02DD> <7E> <007E> <7F> <00A8> endbfchar endcmap CMapName currentdict /CMap defineresource pop end end %%EndResource %%EOF }\endgroup \expandafter\edef\csname cmapOT1\endcsname#1{% \pdffontattr#1{/ToUnicode \the\pdflastobj\space 0 R}% }% % % \cmapOT1IT \begingroup \catcode`\^^M=\active \def^^M{^^J}% Output line endings as the ^^J char. \catcode`\%=12 \immediate\pdfobj stream {%!PS-Adobe-3.0 Resource-CMap %%DocumentNeededResources: ProcSet (CIDInit) %%IncludeResource: ProcSet (CIDInit) %%BeginResource: CMap (TeX-OT1IT-0) %%Title: (TeX-OT1IT-0 TeX OT1IT 0) %%Version: 1.000 %%EndComments /CIDInit /ProcSet findresource begin 12 dict begin begincmap /CIDSystemInfo << /Registry (TeX) /Ordering (OT1IT) /Supplement 0 >> def /CMapName /TeX-OT1IT-0 def /CMapType 2 def 1 begincodespacerange <00> <7F> endcodespacerange 8 beginbfrange <00> <01> <0393> <09> <0A> <03A8> <25> <26> <0025> <28> <3B> <0028> <3F> <5B> <003F> <5D> <5E> <005D> <61> <7A> <0061> <7B> <7C> <2013> endbfrange 42 beginbfchar <02> <0398> <03> <039B> <04> <039E> <05> <03A0> <06> <03A3> <07> <03D2> <08> <03A6> <0B> <00660066> <0C> <00660069> <0D> <0066006C> <0E> <006600660069> <0F> <00660066006C> <10> <0131> <11> <0237> <12> <0060> <13> <00B4> <14> <02C7> <15> <02D8> <16> <00AF> <17> <02DA> <18> <00B8> <19> <00DF> <1A> <00E6> <1B> <0153> <1C> <00F8> <1D> <00C6> <1E> <0152> <1F> <00D8> <21> <0021> <22> <201D> <23> <0023> <24> <00A3> <27> <2019> <3C> <00A1> <3D> <003D> <3E> <00BF> <5C> <201C> <5F> <02D9> <60> <2018> <7D> <02DD> <7E> <007E> <7F> <00A8> endbfchar endcmap CMapName currentdict /CMap defineresource pop end end %%EndResource %%EOF }\endgroup \expandafter\edef\csname cmapOT1IT\endcsname#1{% \pdffontattr#1{/ToUnicode \the\pdflastobj\space 0 R}% }% % % \cmapOT1TT \begingroup \catcode`\^^M=\active \def^^M{^^J}% Output line endings as the ^^J char. \catcode`\%=12 \immediate\pdfobj stream {%!PS-Adobe-3.0 Resource-CMap %%DocumentNeededResources: ProcSet (CIDInit) %%IncludeResource: ProcSet (CIDInit) %%BeginResource: CMap (TeX-OT1TT-0) %%Title: (TeX-OT1TT-0 TeX OT1TT 0) %%Version: 1.000 %%EndComments /CIDInit /ProcSet findresource begin 12 dict begin begincmap /CIDSystemInfo << /Registry (TeX) /Ordering (OT1TT) /Supplement 0 >> def /CMapName /TeX-OT1TT-0 def /CMapType 2 def 1 begincodespacerange <00> <7F> endcodespacerange 5 beginbfrange <00> <01> <0393> <09> <0A> <03A8> <21> <26> <0021> <28> <5F> <0028> <61> <7E> <0061> endbfrange 32 beginbfchar <02> <0398> <03> <039B> <04> <039E> <05> <03A0> <06> <03A3> <07> <03D2> <08> <03A6> <0B> <2191> <0C> <2193> <0D> <0027> <0E> <00A1> <0F> <00BF> <10> <0131> <11> <0237> <12> <0060> <13> <00B4> <14> <02C7> <15> <02D8> <16> <00AF> <17> <02DA> <18> <00B8> <19> <00DF> <1A> <00E6> <1B> <0153> <1C> <00F8> <1D> <00C6> <1E> <0152> <1F> <00D8> <20> <2423> <27> <2019> <60> <2018> <7F> <00A8> endbfchar endcmap CMapName currentdict /CMap defineresource pop end end %%EndResource %%EOF }\endgroup \expandafter\edef\csname cmapOT1TT\endcsname#1{% \pdffontattr#1{/ToUnicode \the\pdflastobj\space 0 R}% }% \else \expandafter\let\csname cmapOT1\endcsname\gobble \expandafter\let\csname cmapOT1IT\endcsname\gobble \expandafter\let\csname cmapOT1TT\endcsname\gobble \fi % Set the font macro #1 to the font named #2, adding on the % specified font prefix (normally `cm'). % #3 is the font's design size, #4 is a scale factor, #5 is the CMap % encoding (currently only OT1, OT1IT and OT1TT are allowed, pass % empty to omit). \def\setfont#1#2#3#4#5{% \font#1=\fontprefix#2#3 scaled #4 \csname cmap#5\endcsname#1% } % This is what gets called when #5 of \setfont is empty. \let\cmap\gobble % Use cm as the default font prefix. % To specify the font prefix, you must define \fontprefix % before you read in texinfo.tex. \ifx\fontprefix\undefined \def\fontprefix{cm} \fi % Support font families that don't use the same naming scheme as CM. \def\rmshape{r} \def\rmbshape{bx} %where the normal face is bold \def\bfshape{b} \def\bxshape{bx} \def\ttshape{tt} \def\ttbshape{tt} \def\ttslshape{sltt} \def\itshape{ti} \def\itbshape{bxti} \def\slshape{sl} \def\slbshape{bxsl} \def\sfshape{ss} \def\sfbshape{ss} \def\scshape{csc} \def\scbshape{csc} % Definitions for a main text size of 11pt. This is the default in % Texinfo. % \def\definetextfontsizexi{% % Text fonts (11.2pt, magstep1). \def\textnominalsize{11pt} \edef\mainmagstep{\magstephalf} \setfont\textrm\rmshape{10}{\mainmagstep}{OT1} \setfont\texttt\ttshape{10}{\mainmagstep}{OT1TT} \setfont\textbf\bfshape{10}{\mainmagstep}{OT1} \setfont\textit\itshape{10}{\mainmagstep}{OT1IT} \setfont\textsl\slshape{10}{\mainmagstep}{OT1} \setfont\textsf\sfshape{10}{\mainmagstep}{OT1} \setfont\textsc\scshape{10}{\mainmagstep}{OT1} \setfont\textttsl\ttslshape{10}{\mainmagstep}{OT1TT} \font\texti=cmmi10 scaled \mainmagstep \font\textsy=cmsy10 scaled \mainmagstep % A few fonts for @defun names and args. \setfont\defbf\bfshape{10}{\magstep1}{OT1} \setfont\deftt\ttshape{10}{\magstep1}{OT1TT} \setfont\defttsl\ttslshape{10}{\magstep1}{OT1TT} \def\df{\let\tentt=\deftt \let\tenbf = \defbf \let\tenttsl=\defttsl \bf} % Fonts for indices, footnotes, small examples (9pt). \def\smallnominalsize{9pt} \setfont\smallrm\rmshape{9}{1000}{OT1} \setfont\smalltt\ttshape{9}{1000}{OT1TT} \setfont\smallbf\bfshape{10}{900}{OT1} \setfont\smallit\itshape{9}{1000}{OT1IT} \setfont\smallsl\slshape{9}{1000}{OT1} \setfont\smallsf\sfshape{9}{1000}{OT1} \setfont\smallsc\scshape{10}{900}{OT1} \setfont\smallttsl\ttslshape{10}{900}{OT1TT} \font\smalli=cmmi9 \font\smallsy=cmsy9 % Fonts for small examples (8pt). \def\smallernominalsize{8pt} \setfont\smallerrm\rmshape{8}{1000}{OT1} \setfont\smallertt\ttshape{8}{1000}{OT1TT} \setfont\smallerbf\bfshape{10}{800}{OT1} \setfont\smallerit\itshape{8}{1000}{OT1IT} \setfont\smallersl\slshape{8}{1000}{OT1} \setfont\smallersf\sfshape{8}{1000}{OT1} \setfont\smallersc\scshape{10}{800}{OT1} \setfont\smallerttsl\ttslshape{10}{800}{OT1TT} \font\smalleri=cmmi8 \font\smallersy=cmsy8 % Fonts for title page (20.4pt): \def\titlenominalsize{20pt} \setfont\titlerm\rmbshape{12}{\magstep3}{OT1} \setfont\titleit\itbshape{10}{\magstep4}{OT1IT} \setfont\titlesl\slbshape{10}{\magstep4}{OT1} \setfont\titlett\ttbshape{12}{\magstep3}{OT1TT} \setfont\titlettsl\ttslshape{10}{\magstep4}{OT1TT} \setfont\titlesf\sfbshape{17}{\magstep1}{OT1} \let\titlebf=\titlerm \setfont\titlesc\scbshape{10}{\magstep4}{OT1} \font\titlei=cmmi12 scaled \magstep3 \font\titlesy=cmsy10 scaled \magstep4 \def\authorrm{\secrm} \def\authortt{\sectt} % Chapter (and unnumbered) fonts (17.28pt). \def\chapnominalsize{17pt} \setfont\chaprm\rmbshape{12}{\magstep2}{OT1} \setfont\chapit\itbshape{10}{\magstep3}{OT1IT} \setfont\chapsl\slbshape{10}{\magstep3}{OT1} \setfont\chaptt\ttbshape{12}{\magstep2}{OT1TT} \setfont\chapttsl\ttslshape{10}{\magstep3}{OT1TT} \setfont\chapsf\sfbshape{17}{1000}{OT1} \let\chapbf=\chaprm \setfont\chapsc\scbshape{10}{\magstep3}{OT1} \font\chapi=cmmi12 scaled \magstep2 \font\chapsy=cmsy10 scaled \magstep3 % Section fonts (14.4pt). \def\secnominalsize{14pt} \setfont\secrm\rmbshape{12}{\magstep1}{OT1} \setfont\secit\itbshape{10}{\magstep2}{OT1IT} \setfont\secsl\slbshape{10}{\magstep2}{OT1} \setfont\sectt\ttbshape{12}{\magstep1}{OT1TT} \setfont\secttsl\ttslshape{10}{\magstep2}{OT1TT} \setfont\secsf\sfbshape{12}{\magstep1}{OT1} \let\secbf\secrm \setfont\secsc\scbshape{10}{\magstep2}{OT1} \font\seci=cmmi12 scaled \magstep1 \font\secsy=cmsy10 scaled \magstep2 % Subsection fonts (13.15pt). \def\ssecnominalsize{13pt} \setfont\ssecrm\rmbshape{12}{\magstephalf}{OT1} \setfont\ssecit\itbshape{10}{1315}{OT1IT} \setfont\ssecsl\slbshape{10}{1315}{OT1} \setfont\ssectt\ttbshape{12}{\magstephalf}{OT1TT} \setfont\ssecttsl\ttslshape{10}{1315}{OT1TT} \setfont\ssecsf\sfbshape{12}{\magstephalf}{OT1} \let\ssecbf\ssecrm \setfont\ssecsc\scbshape{10}{1315}{OT1} \font\sseci=cmmi12 scaled \magstephalf \font\ssecsy=cmsy10 scaled 1315 % Reduced fonts for @acro in text (10pt). \def\reducednominalsize{10pt} \setfont\reducedrm\rmshape{10}{1000}{OT1} \setfont\reducedtt\ttshape{10}{1000}{OT1TT} \setfont\reducedbf\bfshape{10}{1000}{OT1} \setfont\reducedit\itshape{10}{1000}{OT1IT} \setfont\reducedsl\slshape{10}{1000}{OT1} \setfont\reducedsf\sfshape{10}{1000}{OT1} \setfont\reducedsc\scshape{10}{1000}{OT1} \setfont\reducedttsl\ttslshape{10}{1000}{OT1TT} \font\reducedi=cmmi10 \font\reducedsy=cmsy10 % reset the current fonts \textfonts \rm } % end of 11pt text font size definitions % Definitions to make the main text be 10pt Computer Modern, with % section, chapter, etc., sizes following suit. This is for the GNU % Press printing of the Emacs 22 manual. Maybe other manuals in the % future. Used with @smallbook, which sets the leading to 12pt. % \def\definetextfontsizex{% % Text fonts (10pt). \def\textnominalsize{10pt} \edef\mainmagstep{1000} \setfont\textrm\rmshape{10}{\mainmagstep}{OT1} \setfont\texttt\ttshape{10}{\mainmagstep}{OT1TT} \setfont\textbf\bfshape{10}{\mainmagstep}{OT1} \setfont\textit\itshape{10}{\mainmagstep}{OT1IT} \setfont\textsl\slshape{10}{\mainmagstep}{OT1} \setfont\textsf\sfshape{10}{\mainmagstep}{OT1} \setfont\textsc\scshape{10}{\mainmagstep}{OT1} \setfont\textttsl\ttslshape{10}{\mainmagstep}{OT1TT} \font\texti=cmmi10 scaled \mainmagstep \font\textsy=cmsy10 scaled \mainmagstep % A few fonts for @defun names and args. \setfont\defbf\bfshape{10}{\magstephalf}{OT1} \setfont\deftt\ttshape{10}{\magstephalf}{OT1TT} \setfont\defttsl\ttslshape{10}{\magstephalf}{OT1TT} \def\df{\let\tentt=\deftt \let\tenbf = \defbf \let\tenttsl=\defttsl \bf} % Fonts for indices, footnotes, small examples (9pt). \def\smallnominalsize{9pt} \setfont\smallrm\rmshape{9}{1000}{OT1} \setfont\smalltt\ttshape{9}{1000}{OT1TT} \setfont\smallbf\bfshape{10}{900}{OT1} \setfont\smallit\itshape{9}{1000}{OT1IT} \setfont\smallsl\slshape{9}{1000}{OT1} \setfont\smallsf\sfshape{9}{1000}{OT1} \setfont\smallsc\scshape{10}{900}{OT1} \setfont\smallttsl\ttslshape{10}{900}{OT1TT} \font\smalli=cmmi9 \font\smallsy=cmsy9 % Fonts for small examples (8pt). \def\smallernominalsize{8pt} \setfont\smallerrm\rmshape{8}{1000}{OT1} \setfont\smallertt\ttshape{8}{1000}{OT1TT} \setfont\smallerbf\bfshape{10}{800}{OT1} \setfont\smallerit\itshape{8}{1000}{OT1IT} \setfont\smallersl\slshape{8}{1000}{OT1} \setfont\smallersf\sfshape{8}{1000}{OT1} \setfont\smallersc\scshape{10}{800}{OT1} \setfont\smallerttsl\ttslshape{10}{800}{OT1TT} \font\smalleri=cmmi8 \font\smallersy=cmsy8 % Fonts for title page (20.4pt): \def\titlenominalsize{20pt} \setfont\titlerm\rmbshape{12}{\magstep3}{OT1} \setfont\titleit\itbshape{10}{\magstep4}{OT1IT} \setfont\titlesl\slbshape{10}{\magstep4}{OT1} \setfont\titlett\ttbshape{12}{\magstep3}{OT1TT} \setfont\titlettsl\ttslshape{10}{\magstep4}{OT1TT} \setfont\titlesf\sfbshape{17}{\magstep1}{OT1} \let\titlebf=\titlerm \setfont\titlesc\scbshape{10}{\magstep4}{OT1} \font\titlei=cmmi12 scaled \magstep3 \font\titlesy=cmsy10 scaled \magstep4 \def\authorrm{\secrm} \def\authortt{\sectt} % Chapter fonts (14.4pt). \def\chapnominalsize{14pt} \setfont\chaprm\rmbshape{12}{\magstep1}{OT1} \setfont\chapit\itbshape{10}{\magstep2}{OT1IT} \setfont\chapsl\slbshape{10}{\magstep2}{OT1} \setfont\chaptt\ttbshape{12}{\magstep1}{OT1TT} \setfont\chapttsl\ttslshape{10}{\magstep2}{OT1TT} \setfont\chapsf\sfbshape{12}{\magstep1}{OT1} \let\chapbf\chaprm \setfont\chapsc\scbshape{10}{\magstep2}{OT1} \font\chapi=cmmi12 scaled \magstep1 \font\chapsy=cmsy10 scaled \magstep2 % Section fonts (12pt). \def\secnominalsize{12pt} \setfont\secrm\rmbshape{12}{1000}{OT1} \setfont\secit\itbshape{10}{\magstep1}{OT1IT} \setfont\secsl\slbshape{10}{\magstep1}{OT1} \setfont\sectt\ttbshape{12}{1000}{OT1TT} \setfont\secttsl\ttslshape{10}{\magstep1}{OT1TT} \setfont\secsf\sfbshape{12}{1000}{OT1} \let\secbf\secrm \setfont\secsc\scbshape{10}{\magstep1}{OT1} \font\seci=cmmi12 \font\secsy=cmsy10 scaled \magstep1 % Subsection fonts (10pt). \def\ssecnominalsize{10pt} \setfont\ssecrm\rmbshape{10}{1000}{OT1} \setfont\ssecit\itbshape{10}{1000}{OT1IT} \setfont\ssecsl\slbshape{10}{1000}{OT1} \setfont\ssectt\ttbshape{10}{1000}{OT1TT} \setfont\ssecttsl\ttslshape{10}{1000}{OT1TT} \setfont\ssecsf\sfbshape{10}{1000}{OT1} \let\ssecbf\ssecrm \setfont\ssecsc\scbshape{10}{1000}{OT1} \font\sseci=cmmi10 \font\ssecsy=cmsy10 % Reduced fonts for @acro in text (9pt). \def\reducednominalsize{9pt} \setfont\reducedrm\rmshape{9}{1000}{OT1} \setfont\reducedtt\ttshape{9}{1000}{OT1TT} \setfont\reducedbf\bfshape{10}{900}{OT1} \setfont\reducedit\itshape{9}{1000}{OT1IT} \setfont\reducedsl\slshape{9}{1000}{OT1} \setfont\reducedsf\sfshape{9}{1000}{OT1} \setfont\reducedsc\scshape{10}{900}{OT1} \setfont\reducedttsl\ttslshape{10}{900}{OT1TT} \font\reducedi=cmmi9 \font\reducedsy=cmsy9 % reduce space between paragraphs \divide\parskip by 2 % reset the current fonts \textfonts \rm } % end of 10pt text font size definitions % We provide the user-level command % @fonttextsize 10 % (or 11) to redefine the text font size. pt is assumed. % \def\xword{10} \def\xiword{11} % \parseargdef\fonttextsize{% \def\textsizearg{#1}% \wlog{doing @fonttextsize \textsizearg}% % % Set \globaldefs so that documents can use this inside @tex, since % makeinfo 4.8 does not support it, but we need it nonetheless. % \begingroup \globaldefs=1 \ifx\textsizearg\xword \definetextfontsizex \else \ifx\textsizearg\xiword \definetextfontsizexi \else \errhelp=\EMsimple \errmessage{@fonttextsize only supports `10' or `11', not `\textsizearg'} \fi\fi \endgroup } % In order for the font changes to affect most math symbols and letters, % we have to define the \textfont of the standard families. Since % texinfo doesn't allow for producing subscripts and superscripts except % in the main text, we don't bother to reset \scriptfont and % \scriptscriptfont (which would also require loading a lot more fonts). % \def\resetmathfonts{% \textfont0=\tenrm \textfont1=\teni \textfont2=\tensy \textfont\itfam=\tenit \textfont\slfam=\tensl \textfont\bffam=\tenbf \textfont\ttfam=\tentt \textfont\sffam=\tensf } % The font-changing commands redefine the meanings of \tenSTYLE, instead % of just \STYLE. We do this because \STYLE needs to also set the % current \fam for math mode. Our \STYLE (e.g., \rm) commands hardwire % \tenSTYLE to set the current font. % % Each font-changing command also sets the names \lsize (one size lower) % and \lllsize (three sizes lower). These relative commands are used in % the LaTeX logo and acronyms. % % This all needs generalizing, badly. % \def\textfonts{% \let\tenrm=\textrm \let\tenit=\textit \let\tensl=\textsl \let\tenbf=\textbf \let\tentt=\texttt \let\smallcaps=\textsc \let\tensf=\textsf \let\teni=\texti \let\tensy=\textsy \let\tenttsl=\textttsl \def\curfontsize{text}% \def\lsize{reduced}\def\lllsize{smaller}% \resetmathfonts \setleading{\textleading}} \def\titlefonts{% \let\tenrm=\titlerm \let\tenit=\titleit \let\tensl=\titlesl \let\tenbf=\titlebf \let\tentt=\titlett \let\smallcaps=\titlesc \let\tensf=\titlesf \let\teni=\titlei \let\tensy=\titlesy \let\tenttsl=\titlettsl \def\curfontsize{title}% \def\lsize{chap}\def\lllsize{subsec}% \resetmathfonts \setleading{25pt}} \def\titlefont#1{{\titlefonts\rm #1}} \def\chapfonts{% \let\tenrm=\chaprm \let\tenit=\chapit \let\tensl=\chapsl \let\tenbf=\chapbf \let\tentt=\chaptt \let\smallcaps=\chapsc \let\tensf=\chapsf \let\teni=\chapi \let\tensy=\chapsy \let\tenttsl=\chapttsl \def\curfontsize{chap}% \def\lsize{sec}\def\lllsize{text}% \resetmathfonts \setleading{19pt}} \def\secfonts{% \let\tenrm=\secrm \let\tenit=\secit \let\tensl=\secsl \let\tenbf=\secbf \let\tentt=\sectt \let\smallcaps=\secsc \let\tensf=\secsf \let\teni=\seci \let\tensy=\secsy \let\tenttsl=\secttsl \def\curfontsize{sec}% \def\lsize{subsec}\def\lllsize{reduced}% \resetmathfonts \setleading{16pt}} \def\subsecfonts{% \let\tenrm=\ssecrm \let\tenit=\ssecit \let\tensl=\ssecsl \let\tenbf=\ssecbf \let\tentt=\ssectt \let\smallcaps=\ssecsc \let\tensf=\ssecsf \let\teni=\sseci \let\tensy=\ssecsy \let\tenttsl=\ssecttsl \def\curfontsize{ssec}% \def\lsize{text}\def\lllsize{small}% \resetmathfonts \setleading{15pt}} \let\subsubsecfonts = \subsecfonts \def\reducedfonts{% \let\tenrm=\reducedrm \let\tenit=\reducedit \let\tensl=\reducedsl \let\tenbf=\reducedbf \let\tentt=\reducedtt \let\reducedcaps=\reducedsc \let\tensf=\reducedsf \let\teni=\reducedi \let\tensy=\reducedsy \let\tenttsl=\reducedttsl \def\curfontsize{reduced}% \def\lsize{small}\def\lllsize{smaller}% \resetmathfonts \setleading{10.5pt}} \def\smallfonts{% \let\tenrm=\smallrm \let\tenit=\smallit \let\tensl=\smallsl \let\tenbf=\smallbf \let\tentt=\smalltt \let\smallcaps=\smallsc \let\tensf=\smallsf \let\teni=\smalli \let\tensy=\smallsy \let\tenttsl=\smallttsl \def\curfontsize{small}% \def\lsize{smaller}\def\lllsize{smaller}% \resetmathfonts \setleading{10.5pt}} \def\smallerfonts{% \let\tenrm=\smallerrm \let\tenit=\smallerit \let\tensl=\smallersl \let\tenbf=\smallerbf \let\tentt=\smallertt \let\smallcaps=\smallersc \let\tensf=\smallersf \let\teni=\smalleri \let\tensy=\smallersy \let\tenttsl=\smallerttsl \def\curfontsize{smaller}% \def\lsize{smaller}\def\lllsize{smaller}% \resetmathfonts \setleading{9.5pt}} % Set the fonts to use with the @small... environments. \let\smallexamplefonts = \smallfonts % About \smallexamplefonts. If we use \smallfonts (9pt), @smallexample % can fit this many characters: % 8.5x11=86 smallbook=72 a4=90 a5=69 % If we use \scriptfonts (8pt), then we can fit this many characters: % 8.5x11=90+ smallbook=80 a4=90+ a5=77 % For me, subjectively, the few extra characters that fit aren't worth % the additional smallness of 8pt. So I'm making the default 9pt. % % By the way, for comparison, here's what fits with @example (10pt): % 8.5x11=71 smallbook=60 a4=75 a5=58 % % I wish the USA used A4 paper. % --karl, 24jan03. % Set up the default fonts, so we can use them for creating boxes. % \definetextfontsizexi % Define these so they can be easily changed for other fonts. \def\angleleft{$\langle$} \def\angleright{$\rangle$} % Count depth in font-changes, for error checks \newcount\fontdepth \fontdepth=0 % Fonts for short table of contents. \setfont\shortcontrm\rmshape{12}{1000}{OT1} \setfont\shortcontbf\bfshape{10}{\magstep1}{OT1} % no cmb12 \setfont\shortcontsl\slshape{12}{1000}{OT1} \setfont\shortconttt\ttshape{12}{1000}{OT1TT} %% Add scribe-like font environments, plus @l for inline lisp (usually sans %% serif) and @ii for TeX italic % \smartitalic{ARG} outputs arg in italics, followed by an italic correction % unless the following character is such as not to need one. \def\smartitalicx{\ifx\next,\else\ifx\next-\else\ifx\next.\else \ptexslash\fi\fi\fi} \def\smartslanted#1{{\ifusingtt\ttsl\sl #1}\futurelet\next\smartitalicx} \def\smartitalic#1{{\ifusingtt\ttsl\it #1}\futurelet\next\smartitalicx} % like \smartslanted except unconditionally uses \ttsl. % @var is set to this for defun arguments. \def\ttslanted#1{{\ttsl #1}\futurelet\next\smartitalicx} % like \smartslanted except unconditionally use \sl. We never want % ttsl for book titles, do we? \def\cite#1{{\sl #1}\futurelet\next\smartitalicx} \let\i=\smartitalic \let\slanted=\smartslanted \let\var=\smartslanted \let\dfn=\smartslanted \let\emph=\smartitalic % @b, explicit bold. \def\b#1{{\bf #1}} \let\strong=\b % @sansserif, explicit sans. \def\sansserif#1{{\sf #1}} % We can't just use \exhyphenpenalty, because that only has effect at % the end of a paragraph. Restore normal hyphenation at the end of the % group within which \nohyphenation is presumably called. % \def\nohyphenation{\hyphenchar\font = -1 \aftergroup\restorehyphenation} \def\restorehyphenation{\hyphenchar\font = `- } % Set sfcode to normal for the chars that usually have another value. % Can't use plain's \frenchspacing because it uses the `\x notation, and % sometimes \x has an active definition that messes things up. % \catcode`@=11 \def\plainfrenchspacing{% \sfcode\dotChar =\@m \sfcode\questChar=\@m \sfcode\exclamChar=\@m \sfcode\colonChar=\@m \sfcode\semiChar =\@m \sfcode\commaChar =\@m \def\endofsentencespacefactor{1000}% for @. and friends } \def\plainnonfrenchspacing{% \sfcode`\.3000\sfcode`\?3000\sfcode`\!3000 \sfcode`\:2000\sfcode`\;1500\sfcode`\,1250 \def\endofsentencespacefactor{3000}% for @. and friends } \catcode`@=\other \def\endofsentencespacefactor{3000}% default \def\t#1{% {\tt \rawbackslash \plainfrenchspacing #1}% \null } \def\samp#1{`\tclose{#1}'\null} \setfont\keyrm\rmshape{8}{1000}{OT1} \font\keysy=cmsy9 \def\key#1{{\keyrm\textfont2=\keysy \leavevmode\hbox{% \raise0.4pt\hbox{\angleleft}\kern-.08em\vtop{% \vbox{\hrule\kern-0.4pt \hbox{\raise0.4pt\hbox{\vphantom{\angleleft}}#1}}% \kern-0.4pt\hrule}% \kern-.06em\raise0.4pt\hbox{\angleright}}}} \def\key #1{{\nohyphenation \uppercase{#1}}\null} % The old definition, with no lozenge: %\def\key #1{{\ttsl \nohyphenation \uppercase{#1}}\null} \def\ctrl #1{{\tt \rawbackslash \hat}#1} % @file, @option are the same as @samp. \let\file=\samp \let\option=\samp % @code is a modification of @t, % which makes spaces the same size as normal in the surrounding text. \def\tclose#1{% {% % Change normal interword space to be same as for the current font. \spaceskip = \fontdimen2\font % % Switch to typewriter. \tt % % But `\ ' produces the large typewriter interword space. \def\ {{\spaceskip = 0pt{} }}% % % Turn off hyphenation. \nohyphenation % \rawbackslash \plainfrenchspacing #1% }% \null } % We *must* turn on hyphenation at `-' and `_' in @code. % Otherwise, it is too hard to avoid overfull hboxes % in the Emacs manual, the Library manual, etc. % Unfortunately, TeX uses one parameter (\hyphenchar) to control % both hyphenation at - and hyphenation within words. % We must therefore turn them both off (\tclose does that) % and arrange explicitly to hyphenate at a dash. % -- rms. { \catcode`\-=\active \catcode`\_=\active \catcode`\'=\active \catcode`\`=\active % \global\def\code{\begingroup \catcode\rquoteChar=\active \catcode\lquoteChar=\active \let'\codequoteright \let`\codequoteleft % \catcode\dashChar=\active \catcode\underChar=\active \ifallowcodebreaks \let-\codedash \let_\codeunder \else \let-\realdash \let_\realunder \fi \codex } } \def\realdash{-} \def\codedash{-\discretionary{}{}{}} \def\codeunder{% % this is all so @math{@code{var_name}+1} can work. In math mode, _ % is "active" (mathcode"8000) and \normalunderscore (or \char95, etc.) % will therefore expand the active definition of _, which is us % (inside @code that is), therefore an endless loop. \ifusingtt{\ifmmode \mathchar"075F % class 0=ordinary, family 7=ttfam, pos 0x5F=_. \else\normalunderscore \fi \discretionary{}{}{}}% {\_}% } \def\codex #1{\tclose{#1}\endgroup} % An additional complication: the above will allow breaks after, e.g., % each of the four underscores in __typeof__. This is undesirable in % some manuals, especially if they don't have long identifiers in % general. @allowcodebreaks provides a way to control this. % \newif\ifallowcodebreaks \allowcodebreakstrue \def\keywordtrue{true} \def\keywordfalse{false} \parseargdef\allowcodebreaks{% \def\txiarg{#1}% \ifx\txiarg\keywordtrue \allowcodebreakstrue \else\ifx\txiarg\keywordfalse \allowcodebreaksfalse \else \errhelp = \EMsimple \errmessage{Unknown @allowcodebreaks option `\txiarg'}% \fi\fi } % @kbd is like @code, except that if the argument is just one @key command, % then @kbd has no effect. % @kbdinputstyle -- arg is `distinct' (@kbd uses slanted tty font always), % `example' (@kbd uses ttsl only inside of @example and friends), % or `code' (@kbd uses normal tty font always). \parseargdef\kbdinputstyle{% \def\txiarg{#1}% \ifx\txiarg\worddistinct \gdef\kbdexamplefont{\ttsl}\gdef\kbdfont{\ttsl}% \else\ifx\txiarg\wordexample \gdef\kbdexamplefont{\ttsl}\gdef\kbdfont{\tt}% \else\ifx\txiarg\wordcode \gdef\kbdexamplefont{\tt}\gdef\kbdfont{\tt}% \else \errhelp = \EMsimple \errmessage{Unknown @kbdinputstyle option `\txiarg'}% \fi\fi\fi } \def\worddistinct{distinct} \def\wordexample{example} \def\wordcode{code} % Default is `distinct.' \kbdinputstyle distinct \def\xkey{\key} \def\kbdfoo#1#2#3\par{\def\one{#1}\def\three{#3}\def\threex{??}% \ifx\one\xkey\ifx\threex\three \key{#2}% \else{\tclose{\kbdfont\look}}\fi \else{\tclose{\kbdfont\look}}\fi} % For @indicateurl, @env, @command quotes seem unnecessary, so use \code. \let\indicateurl=\code \let\env=\code \let\command=\code % @uref (abbreviation for `urlref') takes an optional (comma-separated) % second argument specifying the text to display and an optional third % arg as text to display instead of (rather than in addition to) the url % itself. First (mandatory) arg is the url. Perhaps eventually put in % a hypertex \special here. % \def\uref#1{\douref #1,,,\finish} \def\douref#1,#2,#3,#4\finish{\begingroup \unsepspaces \pdfurl{#1}% \setbox0 = \hbox{\ignorespaces #3}% \ifdim\wd0 > 0pt \unhbox0 % third arg given, show only that \else \setbox0 = \hbox{\ignorespaces #2}% \ifdim\wd0 > 0pt \ifpdf \unhbox0 % PDF: 2nd arg given, show only it \else \unhbox0\ (\code{#1})% DVI: 2nd arg given, show both it and url \fi \else \code{#1}% only url given, so show it \fi \fi \endlink \endgroup} % @url synonym for @uref, since that's how everyone uses it. % \let\url=\uref % rms does not like angle brackets --karl, 17may97. % So now @email is just like @uref, unless we are pdf. % %\def\email#1{\angleleft{\tt #1}\angleright} \ifpdf \def\email#1{\doemail#1,,\finish} \def\doemail#1,#2,#3\finish{\begingroup \unsepspaces \pdfurl{mailto:#1}% \setbox0 = \hbox{\ignorespaces #2}% \ifdim\wd0>0pt\unhbox0\else\code{#1}\fi \endlink \endgroup} \else \let\email=\uref \fi % Check if we are currently using a typewriter font. Since all the % Computer Modern typewriter fonts have zero interword stretch (and % shrink), and it is reasonable to expect all typewriter fonts to have % this property, we can check that font parameter. % \def\ifmonospace{\ifdim\fontdimen3\font=0pt } % Typeset a dimension, e.g., `in' or `pt'. The only reason for the % argument is to make the input look right: @dmn{pt} instead of @dmn{}pt. % \def\dmn#1{\thinspace #1} \def\kbd#1{\def\look{#1}\expandafter\kbdfoo\look??\par} % @l was never documented to mean ``switch to the Lisp font'', % and it is not used as such in any manual I can find. We need it for % Polish suppressed-l. --karl, 22sep96. %\def\l#1{{\li #1}\null} % Explicit font changes: @r, @sc, undocumented @ii. \def\r#1{{\rm #1}} % roman font \def\sc#1{{\smallcaps#1}} % smallcaps font \def\ii#1{{\it #1}} % italic font % @acronym for "FBI", "NATO", and the like. % We print this one point size smaller, since it's intended for % all-uppercase. % \def\acronym#1{\doacronym #1,,\finish} \def\doacronym#1,#2,#3\finish{% {\selectfonts\lsize #1}% \def\temp{#2}% \ifx\temp\empty \else \space ({\unsepspaces \ignorespaces \temp \unskip})% \fi } % @abbr for "Comput. J." and the like. % No font change, but don't do end-of-sentence spacing. % \def\abbr#1{\doabbr #1,,\finish} \def\doabbr#1,#2,#3\finish{% {\plainfrenchspacing #1}% \def\temp{#2}% \ifx\temp\empty \else \space ({\unsepspaces \ignorespaces \temp \unskip})% \fi } % @pounds{} is a sterling sign, which Knuth put in the CM italic font. % \def\pounds{{\it\$}} % @euro{} comes from a separate font, depending on the current style. % We use the free feym* fonts from the eurosym package by Henrik % Theiling, which support regular, slanted, bold and bold slanted (and % "outlined" (blackboard board, sort of) versions, which we don't need). % It is available from http://www.ctan.org/tex-archive/fonts/eurosym. % % Although only regular is the truly official Euro symbol, we ignore % that. The Euro is designed to be slightly taller than the regular % font height. % % feymr - regular % feymo - slanted % feybr - bold % feybo - bold slanted % % There is no good (free) typewriter version, to my knowledge. % A feymr10 euro is ~7.3pt wide, while a normal cmtt10 char is ~5.25pt wide. % Hmm. % % Also doesn't work in math. Do we need to do math with euro symbols? % Hope not. % % \def\euro{{\eurofont e}} \def\eurofont{% % We set the font at each command, rather than predefining it in % \textfonts and the other font-switching commands, so that % installations which never need the symbol don't have to have the % font installed. % % There is only one designed size (nominal 10pt), so we always scale % that to the current nominal size. % % By the way, simply using "at 1em" works for cmr10 and the like, but % does not work for cmbx10 and other extended/shrunken fonts. % \def\eurosize{\csname\curfontsize nominalsize\endcsname}% % \ifx\curfontstyle\bfstylename % bold: \font\thiseurofont = \ifusingit{feybo10}{feybr10} at \eurosize \else % regular: \font\thiseurofont = \ifusingit{feymo10}{feymr10} at \eurosize \fi \thiseurofont } % @registeredsymbol - R in a circle. The font for the R should really % be smaller yet, but lllsize is the best we can do for now. % Adapted from the plain.tex definition of \copyright. % \def\registeredsymbol{% $^{{\ooalign{\hfil\raise.07ex\hbox{\selectfonts\lllsize R}% \hfil\crcr\Orb}}% }$% } % @textdegree - the normal degrees sign. % \def\textdegree{$^\circ$} % Laurent Siebenmann reports \Orb undefined with: % Textures 1.7.7 (preloaded format=plain 93.10.14) (68K) 16 APR 2004 02:38 % so we'll define it if necessary. % \ifx\Orb\undefined \def\Orb{\mathhexbox20D} \fi \message{page headings,} \newskip\titlepagetopglue \titlepagetopglue = 1.5in \newskip\titlepagebottomglue \titlepagebottomglue = 2pc % First the title page. Must do @settitle before @titlepage. \newif\ifseenauthor \newif\iffinishedtitlepage % Do an implicit @contents or @shortcontents after @end titlepage if the % user says @setcontentsaftertitlepage or @setshortcontentsaftertitlepage. % \newif\ifsetcontentsaftertitlepage \let\setcontentsaftertitlepage = \setcontentsaftertitlepagetrue \newif\ifsetshortcontentsaftertitlepage \let\setshortcontentsaftertitlepage = \setshortcontentsaftertitlepagetrue \parseargdef\shorttitlepage{\begingroup\hbox{}\vskip 1.5in \chaprm \centerline{#1}% \endgroup\page\hbox{}\page} \envdef\titlepage{% % Open one extra group, as we want to close it in the middle of \Etitlepage. \begingroup \parindent=0pt \textfonts % Leave some space at the very top of the page. \vglue\titlepagetopglue % No rule at page bottom unless we print one at the top with @title. \finishedtitlepagetrue % % Most title ``pages'' are actually two pages long, with space % at the top of the second. We don't want the ragged left on the second. \let\oldpage = \page \def\page{% \iffinishedtitlepage\else \finishtitlepage \fi \let\page = \oldpage \page \null }% } \def\Etitlepage{% \iffinishedtitlepage\else \finishtitlepage \fi % It is important to do the page break before ending the group, % because the headline and footline are only empty inside the group. % If we use the new definition of \page, we always get a blank page % after the title page, which we certainly don't want. \oldpage \endgroup % % Need this before the \...aftertitlepage checks so that if they are % in effect the toc pages will come out with page numbers. \HEADINGSon % % If they want short, they certainly want long too. \ifsetshortcontentsaftertitlepage \shortcontents \contents \global\let\shortcontents = \relax \global\let\contents = \relax \fi % \ifsetcontentsaftertitlepage \contents \global\let\contents = \relax \global\let\shortcontents = \relax \fi } \def\finishtitlepage{% \vskip4pt \hrule height 2pt width \hsize \vskip\titlepagebottomglue \finishedtitlepagetrue } %%% Macros to be used within @titlepage: \let\subtitlerm=\tenrm \def\subtitlefont{\subtitlerm \normalbaselineskip = 13pt \normalbaselines} \def\authorfont{\authorrm \normalbaselineskip = 16pt \normalbaselines \let\tt=\authortt} \parseargdef\title{% \checkenv\titlepage \leftline{\titlefonts\rm #1} % print a rule at the page bottom also. \finishedtitlepagefalse \vskip4pt \hrule height 4pt width \hsize \vskip4pt } \parseargdef\subtitle{% \checkenv\titlepage {\subtitlefont \rightline{#1}}% } % @author should come last, but may come many times. % It can also be used inside @quotation. % \parseargdef\author{% \def\temp{\quotation}% \ifx\thisenv\temp \def\quotationauthor{#1}% printed in \Equotation. \else \checkenv\titlepage \ifseenauthor\else \vskip 0pt plus 1filll \seenauthortrue \fi {\authorfont \leftline{#1}}% \fi } %%% Set up page headings and footings. \let\thispage=\folio \newtoks\evenheadline % headline on even pages \newtoks\oddheadline % headline on odd pages \newtoks\evenfootline % footline on even pages \newtoks\oddfootline % footline on odd pages % Now make TeX use those variables \headline={{\textfonts\rm \ifodd\pageno \the\oddheadline \else \the\evenheadline \fi}} \footline={{\textfonts\rm \ifodd\pageno \the\oddfootline \else \the\evenfootline \fi}\HEADINGShook} \let\HEADINGShook=\relax % Commands to set those variables. % For example, this is what @headings on does % @evenheading @thistitle|@thispage|@thischapter % @oddheading @thischapter|@thispage|@thistitle % @evenfooting @thisfile|| % @oddfooting ||@thisfile \def\evenheading{\parsearg\evenheadingxxx} \def\evenheadingxxx #1{\evenheadingyyy #1\|\|\|\|\finish} \def\evenheadingyyy #1\|#2\|#3\|#4\finish{% \global\evenheadline={\rlap{\centerline{#2}}\line{#1\hfil#3}}} \def\oddheading{\parsearg\oddheadingxxx} \def\oddheadingxxx #1{\oddheadingyyy #1\|\|\|\|\finish} \def\oddheadingyyy #1\|#2\|#3\|#4\finish{% \global\oddheadline={\rlap{\centerline{#2}}\line{#1\hfil#3}}} \parseargdef\everyheading{\oddheadingxxx{#1}\evenheadingxxx{#1}}% \def\evenfooting{\parsearg\evenfootingxxx} \def\evenfootingxxx #1{\evenfootingyyy #1\|\|\|\|\finish} \def\evenfootingyyy #1\|#2\|#3\|#4\finish{% \global\evenfootline={\rlap{\centerline{#2}}\line{#1\hfil#3}}} \def\oddfooting{\parsearg\oddfootingxxx} \def\oddfootingxxx #1{\oddfootingyyy #1\|\|\|\|\finish} \def\oddfootingyyy #1\|#2\|#3\|#4\finish{% \global\oddfootline = {\rlap{\centerline{#2}}\line{#1\hfil#3}}% % % Leave some space for the footline. Hopefully ok to assume % @evenfooting will not be used by itself. \global\advance\pageheight by -12pt \global\advance\vsize by -12pt } \parseargdef\everyfooting{\oddfootingxxx{#1}\evenfootingxxx{#1}} % @headings double turns headings on for double-sided printing. % @headings single turns headings on for single-sided printing. % @headings off turns them off. % @headings on same as @headings double, retained for compatibility. % @headings after turns on double-sided headings after this page. % @headings doubleafter turns on double-sided headings after this page. % @headings singleafter turns on single-sided headings after this page. % By default, they are off at the start of a document, % and turned `on' after @end titlepage. \def\headings #1 {\csname HEADINGS#1\endcsname} \def\HEADINGSoff{% \global\evenheadline={\hfil} \global\evenfootline={\hfil} \global\oddheadline={\hfil} \global\oddfootline={\hfil}} \HEADINGSoff % When we turn headings on, set the page number to 1. % For double-sided printing, put current file name in lower left corner, % chapter name on inside top of right hand pages, document % title on inside top of left hand pages, and page numbers on outside top % edge of all pages. \def\HEADINGSdouble{% \global\pageno=1 \global\evenfootline={\hfil} \global\oddfootline={\hfil} \global\evenheadline={\line{\folio\hfil\thistitle}} \global\oddheadline={\line{\thischapter\hfil\folio}} \global\let\contentsalignmacro = \chapoddpage } \let\contentsalignmacro = \chappager % For single-sided printing, chapter title goes across top left of page, % page number on top right. \def\HEADINGSsingle{% \global\pageno=1 \global\evenfootline={\hfil} \global\oddfootline={\hfil} \global\evenheadline={\line{\thischapter\hfil\folio}} \global\oddheadline={\line{\thischapter\hfil\folio}} \global\let\contentsalignmacro = \chappager } \def\HEADINGSon{\HEADINGSdouble} \def\HEADINGSafter{\let\HEADINGShook=\HEADINGSdoublex} \let\HEADINGSdoubleafter=\HEADINGSafter \def\HEADINGSdoublex{% \global\evenfootline={\hfil} \global\oddfootline={\hfil} \global\evenheadline={\line{\folio\hfil\thistitle}} \global\oddheadline={\line{\thischapter\hfil\folio}} \global\let\contentsalignmacro = \chapoddpage } \def\HEADINGSsingleafter{\let\HEADINGShook=\HEADINGSsinglex} \def\HEADINGSsinglex{% \global\evenfootline={\hfil} \global\oddfootline={\hfil} \global\evenheadline={\line{\thischapter\hfil\folio}} \global\oddheadline={\line{\thischapter\hfil\folio}} \global\let\contentsalignmacro = \chappager } % Subroutines used in generating headings % This produces Day Month Year style of output. % Only define if not already defined, in case a txi-??.tex file has set % up a different format (e.g., txi-cs.tex does this). \ifx\today\undefined \def\today{% \number\day\space \ifcase\month \or\putwordMJan\or\putwordMFeb\or\putwordMMar\or\putwordMApr \or\putwordMMay\or\putwordMJun\or\putwordMJul\or\putwordMAug \or\putwordMSep\or\putwordMOct\or\putwordMNov\or\putwordMDec \fi \space\number\year} \fi % @settitle line... specifies the title of the document, for headings. % It generates no output of its own. \def\thistitle{\putwordNoTitle} \def\settitle{\parsearg{\gdef\thistitle}} \message{tables,} % Tables -- @table, @ftable, @vtable, @item(x). % default indentation of table text \newdimen\tableindent \tableindent=.8in % default indentation of @itemize and @enumerate text \newdimen\itemindent \itemindent=.3in % margin between end of table item and start of table text. \newdimen\itemmargin \itemmargin=.1in % used internally for \itemindent minus \itemmargin \newdimen\itemmax % Note @table, @ftable, and @vtable define @item, @itemx, etc., with % these defs. % They also define \itemindex % to index the item name in whatever manner is desired (perhaps none). \newif\ifitemxneedsnegativevskip \def\itemxpar{\par\ifitemxneedsnegativevskip\nobreak\vskip-\parskip\nobreak\fi} \def\internalBitem{\smallbreak \parsearg\itemzzz} \def\internalBitemx{\itemxpar \parsearg\itemzzz} \def\itemzzz #1{\begingroup % \advance\hsize by -\rightskip \advance\hsize by -\tableindent \setbox0=\hbox{\itemindicate{#1}}% \itemindex{#1}% \nobreak % This prevents a break before @itemx. % % If the item text does not fit in the space we have, put it on a line % by itself, and do not allow a page break either before or after that % line. We do not start a paragraph here because then if the next % command is, e.g., @kindex, the whatsit would get put into the % horizontal list on a line by itself, resulting in extra blank space. \ifdim \wd0>\itemmax % % Make this a paragraph so we get the \parskip glue and wrapping, % but leave it ragged-right. \begingroup \advance\leftskip by-\tableindent \advance\hsize by\tableindent \advance\rightskip by0pt plus1fil \leavevmode\unhbox0\par \endgroup % % We're going to be starting a paragraph, but we don't want the % \parskip glue -- logically it's part of the @item we just started. \nobreak \vskip-\parskip % % Stop a page break at the \parskip glue coming up. However, if % what follows is an environment such as @example, there will be no % \parskip glue; then the negative vskip we just inserted would % cause the example and the item to crash together. So we use this % bizarre value of 10001 as a signal to \aboveenvbreak to insert % \parskip glue after all. Section titles are handled this way also. % \penalty 10001 \endgroup \itemxneedsnegativevskipfalse \else % The item text fits into the space. Start a paragraph, so that the % following text (if any) will end up on the same line. \noindent % Do this with kerns and \unhbox so that if there is a footnote in % the item text, it can migrate to the main vertical list and % eventually be printed. \nobreak\kern-\tableindent \dimen0 = \itemmax \advance\dimen0 by \itemmargin \advance\dimen0 by -\wd0 \unhbox0 \nobreak\kern\dimen0 \endgroup \itemxneedsnegativevskiptrue \fi } \def\item{\errmessage{@item while not in a list environment}} \def\itemx{\errmessage{@itemx while not in a list environment}} % @table, @ftable, @vtable. \envdef\table{% \let\itemindex\gobble \tablecheck{table}% } \envdef\ftable{% \def\itemindex ##1{\doind {fn}{\code{##1}}}% \tablecheck{ftable}% } \envdef\vtable{% \def\itemindex ##1{\doind {vr}{\code{##1}}}% \tablecheck{vtable}% } \def\tablecheck#1{% \ifnum \the\catcode`\^^M=\active \endgroup \errmessage{This command won't work in this context; perhaps the problem is that we are \inenvironment\thisenv}% \def\next{\doignore{#1}}% \else \let\next\tablex \fi \next } \def\tablex#1{% \def\itemindicate{#1}% \parsearg\tabley } \def\tabley#1{% {% \makevalueexpandable \edef\temp{\noexpand\tablez #1\space\space\space}% \expandafter }\temp \endtablez } \def\tablez #1 #2 #3 #4\endtablez{% \aboveenvbreak \ifnum 0#1>0 \advance \leftskip by #1\mil \fi \ifnum 0#2>0 \tableindent=#2\mil \fi \ifnum 0#3>0 \advance \rightskip by #3\mil \fi \itemmax=\tableindent \advance \itemmax by -\itemmargin \advance \leftskip by \tableindent \exdentamount=\tableindent \parindent = 0pt \parskip = \smallskipamount \ifdim \parskip=0pt \parskip=2pt \fi \let\item = \internalBitem \let\itemx = \internalBitemx } \def\Etable{\endgraf\afterenvbreak} \let\Eftable\Etable \let\Evtable\Etable \let\Eitemize\Etable \let\Eenumerate\Etable % This is the counter used by @enumerate, which is really @itemize \newcount \itemno \envdef\itemize{\parsearg\doitemize} \def\doitemize#1{% \aboveenvbreak \itemmax=\itemindent \advance\itemmax by -\itemmargin \advance\leftskip by \itemindent \exdentamount=\itemindent \parindent=0pt \parskip=\smallskipamount \ifdim\parskip=0pt \parskip=2pt \fi \def\itemcontents{#1}% % @itemize with no arg is equivalent to @itemize @bullet. \ifx\itemcontents\empty\def\itemcontents{\bullet}\fi \let\item=\itemizeitem } % Definition of @item while inside @itemize and @enumerate. % \def\itemizeitem{% \advance\itemno by 1 % for enumerations {\let\par=\endgraf \smallbreak}% reasonable place to break {% % If the document has an @itemize directly after a section title, a % \nobreak will be last on the list, and \sectionheading will have % done a \vskip-\parskip. In that case, we don't want to zero % parskip, or the item text will crash with the heading. On the % other hand, when there is normal text preceding the item (as there % usually is), we do want to zero parskip, or there would be too much % space. In that case, we won't have a \nobreak before. At least % that's the theory. \ifnum\lastpenalty<10000 \parskip=0in \fi \noindent \hbox to 0pt{\hss \itemcontents \kern\itemmargin}% \vadjust{\penalty 1200}}% not good to break after first line of item. \flushcr } % \splitoff TOKENS\endmark defines \first to be the first token in % TOKENS, and \rest to be the remainder. % \def\splitoff#1#2\endmark{\def\first{#1}\def\rest{#2}}% % Allow an optional argument of an uppercase letter, lowercase letter, % or number, to specify the first label in the enumerated list. No % argument is the same as `1'. % \envparseargdef\enumerate{\enumeratey #1 \endenumeratey} \def\enumeratey #1 #2\endenumeratey{% % If we were given no argument, pretend we were given `1'. \def\thearg{#1}% \ifx\thearg\empty \def\thearg{1}\fi % % Detect if the argument is a single token. If so, it might be a % letter. Otherwise, the only valid thing it can be is a number. % (We will always have one token, because of the test we just made. % This is a good thing, since \splitoff doesn't work given nothing at % all -- the first parameter is undelimited.) \expandafter\splitoff\thearg\endmark \ifx\rest\empty % Only one token in the argument. It could still be anything. % A ``lowercase letter'' is one whose \lccode is nonzero. % An ``uppercase letter'' is one whose \lccode is both nonzero, and % not equal to itself. % Otherwise, we assume it's a number. % % We need the \relax at the end of the \ifnum lines to stop TeX from % continuing to look for a . % \ifnum\lccode\expandafter`\thearg=0\relax \numericenumerate % a number (we hope) \else % It's a letter. \ifnum\lccode\expandafter`\thearg=\expandafter`\thearg\relax \lowercaseenumerate % lowercase letter \else \uppercaseenumerate % uppercase letter \fi \fi \else % Multiple tokens in the argument. We hope it's a number. \numericenumerate \fi } % An @enumerate whose labels are integers. The starting integer is % given in \thearg. % \def\numericenumerate{% \itemno = \thearg \startenumeration{\the\itemno}% } % The starting (lowercase) letter is in \thearg. \def\lowercaseenumerate{% \itemno = \expandafter`\thearg \startenumeration{% % Be sure we're not beyond the end of the alphabet. \ifnum\itemno=0 \errmessage{No more lowercase letters in @enumerate; get a bigger alphabet}% \fi \char\lccode\itemno }% } % The starting (uppercase) letter is in \thearg. \def\uppercaseenumerate{% \itemno = \expandafter`\thearg \startenumeration{% % Be sure we're not beyond the end of the alphabet. \ifnum\itemno=0 \errmessage{No more uppercase letters in @enumerate; get a bigger alphabet} \fi \char\uccode\itemno }% } % Call \doitemize, adding a period to the first argument and supplying the % common last two arguments. Also subtract one from the initial value in % \itemno, since @item increments \itemno. % \def\startenumeration#1{% \advance\itemno by -1 \doitemize{#1.}\flushcr } % @alphaenumerate and @capsenumerate are abbreviations for giving an arg % to @enumerate. % \def\alphaenumerate{\enumerate{a}} \def\capsenumerate{\enumerate{A}} \def\Ealphaenumerate{\Eenumerate} \def\Ecapsenumerate{\Eenumerate} % @multitable macros % Amy Hendrickson, 8/18/94, 3/6/96 % % @multitable ... @end multitable will make as many columns as desired. % Contents of each column will wrap at width given in preamble. Width % can be specified either with sample text given in a template line, % or in percent of \hsize, the current width of text on page. % Table can continue over pages but will only break between lines. % To make preamble: % % Either define widths of columns in terms of percent of \hsize: % @multitable @columnfractions .25 .3 .45 % @item ... % % Numbers following @columnfractions are the percent of the total % current hsize to be used for each column. You may use as many % columns as desired. % Or use a template: % @multitable {Column 1 template} {Column 2 template} {Column 3 template} % @item ... % using the widest term desired in each column. % Each new table line starts with @item, each subsequent new column % starts with @tab. Empty columns may be produced by supplying @tab's % with nothing between them for as many times as empty columns are needed, % ie, @tab@tab@tab will produce two empty columns. % @item, @tab do not need to be on their own lines, but it will not hurt % if they are. % Sample multitable: % @multitable {Column 1 template} {Column 2 template} {Column 3 template} % @item first col stuff @tab second col stuff @tab third col % @item % first col stuff % @tab % second col stuff % @tab % third col % @item first col stuff @tab second col stuff % @tab Many paragraphs of text may be used in any column. % % They will wrap at the width determined by the template. % @item@tab@tab This will be in third column. % @end multitable % Default dimensions may be reset by user. % @multitableparskip is vertical space between paragraphs in table. % @multitableparindent is paragraph indent in table. % @multitablecolmargin is horizontal space to be left between columns. % @multitablelinespace is space to leave between table items, baseline % to baseline. % 0pt means it depends on current normal line spacing. % \newskip\multitableparskip \newskip\multitableparindent \newdimen\multitablecolspace \newskip\multitablelinespace \multitableparskip=0pt \multitableparindent=6pt \multitablecolspace=12pt \multitablelinespace=0pt % Macros used to set up halign preamble: % \let\endsetuptable\relax \def\xendsetuptable{\endsetuptable} \let\columnfractions\relax \def\xcolumnfractions{\columnfractions} \newif\ifsetpercent % #1 is the @columnfraction, usually a decimal number like .5, but might % be just 1. We just use it, whatever it is. % \def\pickupwholefraction#1 {% \global\advance\colcount by 1 \expandafter\xdef\csname col\the\colcount\endcsname{#1\hsize}% \setuptable } \newcount\colcount \def\setuptable#1{% \def\firstarg{#1}% \ifx\firstarg\xendsetuptable \let\go = \relax \else \ifx\firstarg\xcolumnfractions \global\setpercenttrue \else \ifsetpercent \let\go\pickupwholefraction \else \global\advance\colcount by 1 \setbox0=\hbox{#1\unskip\space}% Add a normal word space as a % separator; typically that is always in the input, anyway. \expandafter\xdef\csname col\the\colcount\endcsname{\the\wd0}% \fi \fi \ifx\go\pickupwholefraction % Put the argument back for the \pickupwholefraction call, so % we'll always have a period there to be parsed. \def\go{\pickupwholefraction#1}% \else \let\go = \setuptable \fi% \fi \go } % multitable-only commands. % % @headitem starts a heading row, which we typeset in bold. % Assignments have to be global since we are inside the implicit group % of an alignment entry. Note that \everycr resets \everytab. \def\headitem{\checkenv\multitable \crcr \global\everytab={\bf}\the\everytab}% % % A \tab used to include \hskip1sp. But then the space in a template % line is not enough. That is bad. So let's go back to just `&' until % we encounter the problem it was intended to solve again. % --karl, nathan@acm.org, 20apr99. \def\tab{\checkenv\multitable &\the\everytab}% % @multitable ... @end multitable definitions: % \newtoks\everytab % insert after every tab. % \envdef\multitable{% \vskip\parskip \startsavinginserts % % @item within a multitable starts a normal row. % We use \def instead of \let so that if one of the multitable entries % contains an @itemize, we don't choke on the \item (seen as \crcr aka % \endtemplate) expanding \doitemize. \def\item{\crcr}% % \tolerance=9500 \hbadness=9500 \setmultitablespacing \parskip=\multitableparskip \parindent=\multitableparindent \overfullrule=0pt \global\colcount=0 % \everycr = {% \noalign{% \global\everytab={}% \global\colcount=0 % Reset the column counter. % Check for saved footnotes, etc. \checkinserts % Keeps underfull box messages off when table breaks over pages. %\filbreak % Maybe so, but it also creates really weird page breaks when the % table breaks over pages. Wouldn't \vfil be better? Wait until the % problem manifests itself, so it can be fixed for real --karl. }% }% % \parsearg\domultitable } \def\domultitable#1{% % To parse everything between @multitable and @item: \setuptable#1 \endsetuptable % % This preamble sets up a generic column definition, which will % be used as many times as user calls for columns. % \vtop will set a single line and will also let text wrap and % continue for many paragraphs if desired. \halign\bgroup &% \global\advance\colcount by 1 \multistrut \vtop{% % Use the current \colcount to find the correct column width: \hsize=\expandafter\csname col\the\colcount\endcsname % % In order to keep entries from bumping into each other % we will add a \leftskip of \multitablecolspace to all columns after % the first one. % % If a template has been used, we will add \multitablecolspace % to the width of each template entry. % % If the user has set preamble in terms of percent of \hsize we will % use that dimension as the width of the column, and the \leftskip % will keep entries from bumping into each other. Table will start at % left margin and final column will justify at right margin. % % Make sure we don't inherit \rightskip from the outer environment. \rightskip=0pt \ifnum\colcount=1 % The first column will be indented with the surrounding text. \advance\hsize by\leftskip \else \ifsetpercent \else % If user has not set preamble in terms of percent of \hsize % we will advance \hsize by \multitablecolspace. \advance\hsize by \multitablecolspace \fi % In either case we will make \leftskip=\multitablecolspace: \leftskip=\multitablecolspace \fi % Ignoring space at the beginning and end avoids an occasional spurious % blank line, when TeX decides to break the line at the space before the % box from the multistrut, so the strut ends up on a line by itself. % For example: % @multitable @columnfractions .11 .89 % @item @code{#} % @tab Legal holiday which is valid in major parts of the whole country. % Is automatically provided with highlighting sequences respectively % marking characters. \noindent\ignorespaces##\unskip\multistrut }\cr } \def\Emultitable{% \crcr \egroup % end the \halign \global\setpercentfalse } \def\setmultitablespacing{% \def\multistrut{\strut}% just use the standard line spacing % % Compute \multitablelinespace (if not defined by user) for use in % \multitableparskip calculation. We used define \multistrut based on % this, but (ironically) that caused the spacing to be off. % See bug-texinfo report from Werner Lemberg, 31 Oct 2004 12:52:20 +0100. \ifdim\multitablelinespace=0pt \setbox0=\vbox{X}\global\multitablelinespace=\the\baselineskip \global\advance\multitablelinespace by-\ht0 \fi %% Test to see if parskip is larger than space between lines of %% table. If not, do nothing. %% If so, set to same dimension as multitablelinespace. \ifdim\multitableparskip>\multitablelinespace \global\multitableparskip=\multitablelinespace \global\advance\multitableparskip-7pt %% to keep parskip somewhat smaller %% than skip between lines in the table. \fi% \ifdim\multitableparskip=0pt \global\multitableparskip=\multitablelinespace \global\advance\multitableparskip-7pt %% to keep parskip somewhat smaller %% than skip between lines in the table. \fi} \message{conditionals,} % @iftex, @ifnotdocbook, @ifnothtml, @ifnotinfo, @ifnotplaintext, % @ifnotxml always succeed. They currently do nothing; we don't % attempt to check whether the conditionals are properly nested. But we % have to remember that they are conditionals, so that @end doesn't % attempt to close an environment group. % \def\makecond#1{% \expandafter\let\csname #1\endcsname = \relax \expandafter\let\csname iscond.#1\endcsname = 1 } \makecond{iftex} \makecond{ifnotdocbook} \makecond{ifnothtml} \makecond{ifnotinfo} \makecond{ifnotplaintext} \makecond{ifnotxml} % Ignore @ignore, @ifhtml, @ifinfo, and the like. % \def\direntry{\doignore{direntry}} \def\documentdescription{\doignore{documentdescription}} \def\docbook{\doignore{docbook}} \def\html{\doignore{html}} \def\ifdocbook{\doignore{ifdocbook}} \def\ifhtml{\doignore{ifhtml}} \def\ifinfo{\doignore{ifinfo}} \def\ifnottex{\doignore{ifnottex}} \def\ifplaintext{\doignore{ifplaintext}} \def\ifxml{\doignore{ifxml}} \def\ignore{\doignore{ignore}} \def\menu{\doignore{menu}} \def\xml{\doignore{xml}} % Ignore text until a line `@end #1', keeping track of nested conditionals. % % A count to remember the depth of nesting. \newcount\doignorecount \def\doignore#1{\begingroup % Scan in ``verbatim'' mode: \obeylines \catcode`\@ = \other \catcode`\{ = \other \catcode`\} = \other % % Make sure that spaces turn into tokens that match what \doignoretext wants. \spaceisspace % % Count number of #1's that we've seen. \doignorecount = 0 % % Swallow text until we reach the matching `@end #1'. \dodoignore{#1}% } { \catcode`_=11 % We want to use \_STOP_ which cannot appear in texinfo source. \obeylines % % \gdef\dodoignore#1{% % #1 contains the command name as a string, e.g., `ifinfo'. % % Define a command to find the next `@end #1'. \long\def\doignoretext##1^^M@end #1{% \doignoretextyyy##1^^M@#1\_STOP_}% % % And this command to find another #1 command, at the beginning of a % line. (Otherwise, we would consider a line `@c @ifset', for % example, to count as an @ifset for nesting.) \long\def\doignoretextyyy##1^^M@#1##2\_STOP_{\doignoreyyy{##2}\_STOP_}% % % And now expand that command. \doignoretext ^^M% }% } \def\doignoreyyy#1{% \def\temp{#1}% \ifx\temp\empty % Nothing found. \let\next\doignoretextzzz \else % Found a nested condition, ... \advance\doignorecount by 1 \let\next\doignoretextyyy % ..., look for another. % If we're here, #1 ends with ^^M\ifinfo (for example). \fi \next #1% the token \_STOP_ is present just after this macro. } % We have to swallow the remaining "\_STOP_". % \def\doignoretextzzz#1{% \ifnum\doignorecount = 0 % We have just found the outermost @end. \let\next\enddoignore \else % Still inside a nested condition. \advance\doignorecount by -1 \let\next\doignoretext % Look for the next @end. \fi \next } % Finish off ignored text. { \obeylines% % Ignore anything after the last `@end #1'; this matters in verbatim % environments, where otherwise the newline after an ignored conditional % would result in a blank line in the output. \gdef\enddoignore#1^^M{\endgroup\ignorespaces}% } % @set VAR sets the variable VAR to an empty value. % @set VAR REST-OF-LINE sets VAR to the value REST-OF-LINE. % % Since we want to separate VAR from REST-OF-LINE (which might be % empty), we can't just use \parsearg; we have to insert a space of our % own to delimit the rest of the line, and then take it out again if we % didn't need it. % We rely on the fact that \parsearg sets \catcode`\ =10. % \parseargdef\set{\setyyy#1 \endsetyyy} \def\setyyy#1 #2\endsetyyy{% {% \makevalueexpandable \def\temp{#2}% \edef\next{\gdef\makecsname{SET#1}}% \ifx\temp\empty \next{}% \else \setzzz#2\endsetzzz \fi }% } % Remove the trailing space \setxxx inserted. \def\setzzz#1 \endsetzzz{\next{#1}} % @clear VAR clears (i.e., unsets) the variable VAR. % \parseargdef\clear{% {% \makevalueexpandable \global\expandafter\let\csname SET#1\endcsname=\relax }% } % @value{foo} gets the text saved in variable foo. \def\value{\begingroup\makevalueexpandable\valuexxx} \def\valuexxx#1{\expandablevalue{#1}\endgroup} { \catcode`\- = \active \catcode`\_ = \active % \gdef\makevalueexpandable{% \let\value = \expandablevalue % We don't want these characters active, ... \catcode`\-=\other \catcode`\_=\other % ..., but we might end up with active ones in the argument if % we're called from @code, as @code{@value{foo-bar_}}, though. % So \let them to their normal equivalents. \let-\realdash \let_\normalunderscore } } % We have this subroutine so that we can handle at least some @value's % properly in indexes (we call \makevalueexpandable in \indexdummies). % The command has to be fully expandable (if the variable is set), since % the result winds up in the index file. This means that if the % variable's value contains other Texinfo commands, it's almost certain % it will fail (although perhaps we could fix that with sufficient work % to do a one-level expansion on the result, instead of complete). % \def\expandablevalue#1{% \expandafter\ifx\csname SET#1\endcsname\relax {[No value for ``#1'']}% \message{Variable `#1', used in @value, is not set.}% \else \csname SET#1\endcsname \fi } % @ifset VAR ... @end ifset reads the `...' iff VAR has been defined % with @set. % % To get special treatment of `@end ifset,' call \makeond and the redefine. % \makecond{ifset} \def\ifset{\parsearg{\doifset{\let\next=\ifsetfail}}} \def\doifset#1#2{% {% \makevalueexpandable \let\next=\empty \expandafter\ifx\csname SET#2\endcsname\relax #1% If not set, redefine \next. \fi \expandafter }\next } \def\ifsetfail{\doignore{ifset}} % @ifclear VAR ... @end ifclear reads the `...' iff VAR has never been % defined with @set, or has been undefined with @clear. % % The `\else' inside the `\doifset' parameter is a trick to reuse the % above code: if the variable is not set, do nothing, if it is set, % then redefine \next to \ifclearfail. % \makecond{ifclear} \def\ifclear{\parsearg{\doifset{\else \let\next=\ifclearfail}}} \def\ifclearfail{\doignore{ifclear}} % @dircategory CATEGORY -- specify a category of the dir file % which this file should belong to. Ignore this in TeX. \let\dircategory=\comment % @defininfoenclose. \let\definfoenclose=\comment \message{indexing,} % Index generation facilities % Define \newwrite to be identical to plain tex's \newwrite % except not \outer, so it can be used within macros and \if's. \edef\newwrite{\makecsname{ptexnewwrite}} % \newindex {foo} defines an index named foo. % It automatically defines \fooindex such that % \fooindex ...rest of line... puts an entry in the index foo. % It also defines \fooindfile to be the number of the output channel for % the file that accumulates this index. The file's extension is foo. % The name of an index should be no more than 2 characters long % for the sake of vms. % \def\newindex#1{% \iflinks \expandafter\newwrite \csname#1indfile\endcsname \openout \csname#1indfile\endcsname \jobname.#1 % Open the file \fi \expandafter\xdef\csname#1index\endcsname{% % Define @#1index \noexpand\doindex{#1}} } % @defindex foo == \newindex{foo} % \def\defindex{\parsearg\newindex} % Define @defcodeindex, like @defindex except put all entries in @code. % \def\defcodeindex{\parsearg\newcodeindex} % \def\newcodeindex#1{% \iflinks \expandafter\newwrite \csname#1indfile\endcsname \openout \csname#1indfile\endcsname \jobname.#1 \fi \expandafter\xdef\csname#1index\endcsname{% \noexpand\docodeindex{#1}}% } % @synindex foo bar makes index foo feed into index bar. % Do this instead of @defindex foo if you don't want it as a separate index. % % @syncodeindex foo bar similar, but put all entries made for index foo % inside @code. % \def\synindex#1 #2 {\dosynindex\doindex{#1}{#2}} \def\syncodeindex#1 #2 {\dosynindex\docodeindex{#1}{#2}} % #1 is \doindex or \docodeindex, #2 the index getting redefined (foo), % #3 the target index (bar). \def\dosynindex#1#2#3{% % Only do \closeout if we haven't already done it, else we'll end up % closing the target index. \expandafter \ifx\csname donesynindex#2\endcsname \undefined % The \closeout helps reduce unnecessary open files; the limit on the % Acorn RISC OS is a mere 16 files. \expandafter\closeout\csname#2indfile\endcsname \expandafter\let\csname\donesynindex#2\endcsname = 1 \fi % redefine \fooindfile: \expandafter\let\expandafter\temp\expandafter=\csname#3indfile\endcsname \expandafter\let\csname#2indfile\endcsname=\temp % redefine \fooindex: \expandafter\xdef\csname#2index\endcsname{\noexpand#1{#3}}% } % Define \doindex, the driver for all \fooindex macros. % Argument #1 is generated by the calling \fooindex macro, % and it is "foo", the name of the index. % \doindex just uses \parsearg; it calls \doind for the actual work. % This is because \doind is more useful to call from other macros. % There is also \dosubind {index}{topic}{subtopic} % which makes an entry in a two-level index such as the operation index. \def\doindex#1{\edef\indexname{#1}\parsearg\singleindexer} \def\singleindexer #1{\doind{\indexname}{#1}} % like the previous two, but they put @code around the argument. \def\docodeindex#1{\edef\indexname{#1}\parsearg\singlecodeindexer} \def\singlecodeindexer #1{\doind{\indexname}{\code{#1}}} % Take care of Texinfo commands that can appear in an index entry. % Since there are some commands we want to expand, and others we don't, % we have to laboriously prevent expansion for those that we don't. % \def\indexdummies{% \escapechar = `\\ % use backslash in output files. \def\@{@}% change to @@ when we switch to @ as escape char in index files. \def\ {\realbackslash\space }% % % Need these in case \tex is in effect and \{ is a \delimiter again. % But can't use \lbracecmd and \rbracecmd because texindex assumes % braces and backslashes are used only as delimiters. \let\{ = \mylbrace \let\} = \myrbrace % % I don't entirely understand this, but when an index entry is % generated from a macro call, the \endinput which \scanmacro inserts % causes processing to be prematurely terminated. This is, % apparently, because \indexsorttmp is fully expanded, and \endinput % is an expandable command. The redefinition below makes \endinput % disappear altogether for that purpose -- although logging shows that % processing continues to some further point. On the other hand, it % seems \endinput does not hurt in the printed index arg, since that % is still getting written without apparent harm. % % Sample source (mac-idx3.tex, reported by Graham Percival to % help-texinfo, 22may06): % @macro funindex {WORD} % @findex xyz % @end macro % ... % @funindex commtest % % The above is not enough to reproduce the bug, but it gives the flavor. % % Sample whatsit resulting: % .@write3{\entry{xyz}{@folio }{@code {xyz@endinput }}} % % So: \let\endinput = \empty % % Do the redefinitions. \commondummies } % For the aux and toc files, @ is the escape character. So we want to % redefine everything using @ as the escape character (instead of % \realbackslash, still used for index files). When everything uses @, % this will be simpler. % \def\atdummies{% \def\@{@@}% \def\ {@ }% \let\{ = \lbraceatcmd \let\} = \rbraceatcmd % % Do the redefinitions. \commondummies \otherbackslash } % Called from \indexdummies and \atdummies. % \def\commondummies{% % % \definedummyword defines \#1 as \string\#1\space, thus effectively % preventing its expansion. This is used only for control% words, % not control letters, because the \space would be incorrect for % control characters, but is needed to separate the control word % from whatever follows. % % For control letters, we have \definedummyletter, which omits the % space. % % These can be used both for control words that take an argument and % those that do not. If it is followed by {arg} in the input, then % that will dutifully get written to the index (or wherever). % \def\definedummyword ##1{\def##1{\string##1\space}}% \def\definedummyletter##1{\def##1{\string##1}}% \let\definedummyaccent\definedummyletter % \commondummiesnofonts % \definedummyletter\_% % % Non-English letters. \definedummyword\AA \definedummyword\AE \definedummyword\L \definedummyword\OE \definedummyword\O \definedummyword\aa \definedummyword\ae \definedummyword\l \definedummyword\oe \definedummyword\o \definedummyword\ss \definedummyword\exclamdown \definedummyword\questiondown \definedummyword\ordf \definedummyword\ordm % % Although these internal commands shouldn't show up, sometimes they do. \definedummyword\bf \definedummyword\gtr \definedummyword\hat \definedummyword\less \definedummyword\sf \definedummyword\sl \definedummyword\tclose \definedummyword\tt % \definedummyword\LaTeX \definedummyword\TeX % % Assorted special characters. \definedummyword\bullet \definedummyword\comma \definedummyword\copyright \definedummyword\registeredsymbol \definedummyword\dots \definedummyword\enddots \definedummyword\equiv \definedummyword\error \definedummyword\euro \definedummyword\expansion \definedummyword\minus \definedummyword\pounds \definedummyword\point \definedummyword\print \definedummyword\result \definedummyword\textdegree % % We want to disable all macros so that they are not expanded by \write. \macrolist % \normalturnoffactive % % Handle some cases of @value -- where it does not contain any % (non-fully-expandable) commands. \makevalueexpandable } % \commondummiesnofonts: common to \commondummies and \indexnofonts. % \def\commondummiesnofonts{% % Control letters and accents. \definedummyletter\!% \definedummyaccent\"% \definedummyaccent\'% \definedummyletter\*% \definedummyaccent\,% \definedummyletter\.% \definedummyletter\/% \definedummyletter\:% \definedummyaccent\=% \definedummyletter\?% \definedummyaccent\^% \definedummyaccent\`% \definedummyaccent\~% \definedummyword\u \definedummyword\v \definedummyword\H \definedummyword\dotaccent \definedummyword\ringaccent \definedummyword\tieaccent \definedummyword\ubaraccent \definedummyword\udotaccent \definedummyword\dotless % % Texinfo font commands. \definedummyword\b \definedummyword\i \definedummyword\r \definedummyword\sc \definedummyword\t % % Commands that take arguments. \definedummyword\acronym \definedummyword\cite \definedummyword\code \definedummyword\command \definedummyword\dfn \definedummyword\emph \definedummyword\env \definedummyword\file \definedummyword\kbd \definedummyword\key \definedummyword\math \definedummyword\option \definedummyword\pxref \definedummyword\ref \definedummyword\samp \definedummyword\strong \definedummyword\tie \definedummyword\uref \definedummyword\url \definedummyword\var \definedummyword\verb \definedummyword\w \definedummyword\xref } % \indexnofonts is used when outputting the strings to sort the index % by, and when constructing control sequence names. It eliminates all % control sequences and just writes whatever the best ASCII sort string % would be for a given command (usually its argument). % \def\indexnofonts{% % Accent commands should become @asis. \def\definedummyaccent##1{\let##1\asis}% % We can just ignore other control letters. \def\definedummyletter##1{\let##1\empty}% % Hopefully, all control words can become @asis. \let\definedummyword\definedummyaccent % \commondummiesnofonts % % Don't no-op \tt, since it isn't a user-level command % and is used in the definitions of the active chars like <, >, |, etc. % Likewise with the other plain tex font commands. %\let\tt=\asis % \def\ { }% \def\@{@}% % how to handle braces? \def\_{\normalunderscore}% % % Non-English letters. \def\AA{AA}% \def\AE{AE}% \def\L{L}% \def\OE{OE}% \def\O{O}% \def\aa{aa}% \def\ae{ae}% \def\l{l}% \def\oe{oe}% \def\o{o}% \def\ss{ss}% \def\exclamdown{!}% \def\questiondown{?}% \def\ordf{a}% \def\ordm{o}% % \def\LaTeX{LaTeX}% \def\TeX{TeX}% % % Assorted special characters. % (The following {} will end up in the sort string, but that's ok.) \def\bullet{bullet}% \def\comma{,}% \def\copyright{copyright}% \def\registeredsymbol{R}% \def\dots{...}% \def\enddots{...}% \def\equiv{==}% \def\error{error}% \def\euro{euro}% \def\expansion{==>}% \def\minus{-}% \def\pounds{pounds}% \def\point{.}% \def\print{-|}% \def\result{=>}% \def\textdegree{degrees}% % % We need to get rid of all macros, leaving only the arguments (if present). % Of course this is not nearly correct, but it is the best we can do for now. % makeinfo does not expand macros in the argument to @deffn, which ends up % writing an index entry, and texindex isn't prepared for an index sort entry % that starts with \. % % Since macro invocations are followed by braces, we can just redefine them % to take a single TeX argument. The case of a macro invocation that % goes to end-of-line is not handled. % \macrolist } \let\indexbackslash=0 %overridden during \printindex. \let\SETmarginindex=\relax % put index entries in margin (undocumented)? % Most index entries go through here, but \dosubind is the general case. % #1 is the index name, #2 is the entry text. \def\doind#1#2{\dosubind{#1}{#2}{}} % Workhorse for all \fooindexes. % #1 is name of index, #2 is stuff to put there, #3 is subentry -- % empty if called from \doind, as we usually are (the main exception % is with most defuns, which call us directly). % \def\dosubind#1#2#3{% \iflinks {% % Store the main index entry text (including the third arg). \toks0 = {#2}% % If third arg is present, precede it with a space. \def\thirdarg{#3}% \ifx\thirdarg\empty \else \toks0 = \expandafter{\the\toks0 \space #3}% \fi % \edef\writeto{\csname#1indfile\endcsname}% % \safewhatsit\dosubindwrite }% \fi } % Write the entry in \toks0 to the index file: % \def\dosubindwrite{% % Put the index entry in the margin if desired. \ifx\SETmarginindex\relax\else \insert\margin{\hbox{\vrule height8pt depth3pt width0pt \the\toks0}}% \fi % % Remember, we are within a group. \indexdummies % Must do this here, since \bf, etc expand at this stage \def\backslashcurfont{\indexbackslash}% \indexbackslash isn't defined now % so it will be output as is; and it will print as backslash. % % Process the index entry with all font commands turned off, to % get the string to sort by. {\indexnofonts \edef\temp{\the\toks0}% need full expansion \xdef\indexsorttmp{\temp}% }% % % Set up the complete index entry, with both the sort key and % the original text, including any font commands. We write % three arguments to \entry to the .?? file (four in the % subentry case), texindex reduces to two when writing the .??s % sorted result. \edef\temp{% \write\writeto{% \string\entry{\indexsorttmp}{\noexpand\folio}{\the\toks0}}% }% \temp } % Take care of unwanted page breaks/skips around a whatsit: % % If a skip is the last thing on the list now, preserve it % by backing up by \lastskip, doing the \write, then inserting % the skip again. Otherwise, the whatsit generated by the % \write or \pdfdest will make \lastskip zero. The result is that % sequences like this: % @end defun % @tindex whatever % @defun ... % will have extra space inserted, because the \medbreak in the % start of the @defun won't see the skip inserted by the @end of % the previous defun. % % But don't do any of this if we're not in vertical mode. We % don't want to do a \vskip and prematurely end a paragraph. % % Avoid page breaks due to these extra skips, too. % % But wait, there is a catch there: % We'll have to check whether \lastskip is zero skip. \ifdim is not % sufficient for this purpose, as it ignores stretch and shrink parts % of the skip. The only way seems to be to check the textual % representation of the skip. % % The following is almost like \def\zeroskipmacro{0.0pt} except that % the ``p'' and ``t'' characters have catcode \other, not 11 (letter). % \edef\zeroskipmacro{\expandafter\the\csname z@skip\endcsname} % \newskip\whatsitskip \newcount\whatsitpenalty % % ..., ready, GO: % \def\safewhatsit#1{% \ifhmode #1% \else % \lastskip and \lastpenalty cannot both be nonzero simultaneously. \whatsitskip = \lastskip \edef\lastskipmacro{\the\lastskip}% \whatsitpenalty = \lastpenalty % % If \lastskip is nonzero, that means the last item was a % skip. And since a skip is discardable, that means this % -\skip0 glue we're inserting is preceded by a % non-discardable item, therefore it is not a potential % breakpoint, therefore no \nobreak needed. \ifx\lastskipmacro\zeroskipmacro \else \vskip-\whatsitskip \fi % #1% % \ifx\lastskipmacro\zeroskipmacro % If \lastskip was zero, perhaps the last item was a penalty, and % perhaps it was >=10000, e.g., a \nobreak. In that case, we want % to re-insert the same penalty (values >10000 are used for various % signals); since we just inserted a non-discardable item, any % following glue (such as a \parskip) would be a breakpoint. For example: % % @deffn deffn-whatever % @vindex index-whatever % Description. % would allow a break between the index-whatever whatsit % and the "Description." paragraph. \ifnum\whatsitpenalty>9999 \penalty\whatsitpenalty \fi \else % On the other hand, if we had a nonzero \lastskip, % this make-up glue would be preceded by a non-discardable item % (the whatsit from the \write), so we must insert a \nobreak. \nobreak\vskip\whatsitskip \fi \fi } % The index entry written in the file actually looks like % \entry {sortstring}{page}{topic} % or % \entry {sortstring}{page}{topic}{subtopic} % The texindex program reads in these files and writes files % containing these kinds of lines: % \initial {c} % before the first topic whose initial is c % \entry {topic}{pagelist} % for a topic that is used without subtopics % \primary {topic} % for the beginning of a topic that is used with subtopics % \secondary {subtopic}{pagelist} % for each subtopic. % Define the user-accessible indexing commands % @findex, @vindex, @kindex, @cindex. \def\findex {\fnindex} \def\kindex {\kyindex} \def\cindex {\cpindex} \def\vindex {\vrindex} \def\tindex {\tpindex} \def\pindex {\pgindex} \def\cindexsub {\begingroup\obeylines\cindexsub} {\obeylines % \gdef\cindexsub "#1" #2^^M{\endgroup % \dosubind{cp}{#2}{#1}}} % Define the macros used in formatting output of the sorted index material. % @printindex causes a particular index (the ??s file) to get printed. % It does not print any chapter heading (usually an @unnumbered). % \parseargdef\printindex{\begingroup \dobreak \chapheadingskip{10000}% % \smallfonts \rm \tolerance = 9500 \plainfrenchspacing \everypar = {}% don't want the \kern\-parindent from indentation suppression. % % See if the index file exists and is nonempty. % Change catcode of @ here so that if the index file contains % \initial {@} % as its first line, TeX doesn't complain about mismatched braces % (because it thinks @} is a control sequence). \catcode`\@ = 11 \openin 1 \jobname.#1s \ifeof 1 % \enddoublecolumns gets confused if there is no text in the index, % and it loses the chapter title and the aux file entries for the % index. The easiest way to prevent this problem is to make sure % there is some text. \putwordIndexNonexistent \else % % If the index file exists but is empty, then \openin leaves \ifeof % false. We have to make TeX try to read something from the file, so % it can discover if there is anything in it. \read 1 to \temp \ifeof 1 \putwordIndexIsEmpty \else % Index files are almost Texinfo source, but we use \ as the escape % character. It would be better to use @, but that's too big a change % to make right now. \def\indexbackslash{\backslashcurfont}% \catcode`\\ = 0 \escapechar = `\\ \begindoublecolumns \input \jobname.#1s \enddoublecolumns \fi \fi \closein 1 \endgroup} % These macros are used by the sorted index file itself. % Change them to control the appearance of the index. \def\initial#1{{% % Some minor font changes for the special characters. \let\tentt=\sectt \let\tt=\sectt \let\sf=\sectt % % Remove any glue we may have, we'll be inserting our own. \removelastskip % % We like breaks before the index initials, so insert a bonus. \nobreak \vskip 0pt plus 3\baselineskip \penalty 0 \vskip 0pt plus -3\baselineskip % % Typeset the initial. Making this add up to a whole number of % baselineskips increases the chance of the dots lining up from column % to column. It still won't often be perfect, because of the stretch % we need before each entry, but it's better. % % No shrink because it confuses \balancecolumns. \vskip 1.67\baselineskip plus .5\baselineskip \leftline{\secbf #1}% % Do our best not to break after the initial. \nobreak \vskip .33\baselineskip plus .1\baselineskip }} % \entry typesets a paragraph consisting of the text (#1), dot leaders, and % then page number (#2) flushed to the right margin. It is used for index % and table of contents entries. The paragraph is indented by \leftskip. % % A straightforward implementation would start like this: % \def\entry#1#2{... % But this frozes the catcodes in the argument, and can cause problems to % @code, which sets - active. This problem was fixed by a kludge--- % ``-'' was active throughout whole index, but this isn't really right. % % The right solution is to prevent \entry from swallowing the whole text. % --kasal, 21nov03 \def\entry{% \begingroup % % Start a new paragraph if necessary, so our assignments below can't % affect previous text. \par % % Do not fill out the last line with white space. \parfillskip = 0in % % No extra space above this paragraph. \parskip = 0in % % Do not prefer a separate line ending with a hyphen to fewer lines. \finalhyphendemerits = 0 % % \hangindent is only relevant when the entry text and page number % don't both fit on one line. In that case, bob suggests starting the % dots pretty far over on the line. Unfortunately, a large % indentation looks wrong when the entry text itself is broken across % lines. So we use a small indentation and put up with long leaders. % % \hangafter is reset to 1 (which is the value we want) at the start % of each paragraph, so we need not do anything with that. \hangindent = 2em % % When the entry text needs to be broken, just fill out the first line % with blank space. \rightskip = 0pt plus1fil % % A bit of stretch before each entry for the benefit of balancing % columns. \vskip 0pt plus1pt % % Swallow the left brace of the text (first parameter): \afterassignment\doentry \let\temp = } \def\doentry{% \bgroup % Instead of the swallowed brace. \noindent \aftergroup\finishentry % And now comes the text of the entry. } \def\finishentry#1{% % #1 is the page number. % % The following is kludged to not output a line of dots in the index if % there are no page numbers. The next person who breaks this will be % cursed by a Unix daemon. \def\tempa{{\rm }}% \def\tempb{#1}% \edef\tempc{\tempa}% \edef\tempd{\tempb}% \ifx\tempc\tempd \ % \else % % If we must, put the page number on a line of its own, and fill out % this line with blank space. (The \hfil is overwhelmed with the % fill leaders glue in \indexdotfill if the page number does fit.) \hfil\penalty50 \null\nobreak\indexdotfill % Have leaders before the page number. % % The `\ ' here is removed by the implicit \unskip that TeX does as % part of (the primitive) \par. Without it, a spurious underfull % \hbox ensues. \ifpdf \pdfgettoks#1.% \ \the\toksA \else \ #1% \fi \fi \par \endgroup } % Like plain.tex's \dotfill, except uses up at least 1 em. \def\indexdotfill{\cleaders \hbox{$\mathsurround=0pt \mkern1.5mu.\mkern1.5mu$}\hskip 1em plus 1fill} \def\primary #1{\line{#1\hfil}} \newskip\secondaryindent \secondaryindent=0.5cm \def\secondary#1#2{{% \parfillskip=0in \parskip=0in \hangindent=1in \hangafter=1 \noindent\hskip\secondaryindent\hbox{#1}\indexdotfill \ifpdf \pdfgettoks#2.\ \the\toksA % The page number ends the paragraph. \else #2 \fi \par }} % Define two-column mode, which we use to typeset indexes. % Adapted from the TeXbook, page 416, which is to say, % the manmac.tex format used to print the TeXbook itself. \catcode`\@=11 \newbox\partialpage \newdimen\doublecolumnhsize \def\begindoublecolumns{\begingroup % ended by \enddoublecolumns % Grab any single-column material above us. \output = {% % % Here is a possibility not foreseen in manmac: if we accumulate a % whole lot of material, we might end up calling this \output % routine twice in a row (see the doublecol-lose test, which is % essentially a couple of indexes with @setchapternewpage off). In % that case we just ship out what is in \partialpage with the normal % output routine. Generally, \partialpage will be empty when this % runs and this will be a no-op. See the indexspread.tex test case. \ifvoid\partialpage \else \onepageout{\pagecontents\partialpage}% \fi % \global\setbox\partialpage = \vbox{% % Unvbox the main output page. \unvbox\PAGE \kern-\topskip \kern\baselineskip }% }% \eject % run that output routine to set \partialpage % % Use the double-column output routine for subsequent pages. \output = {\doublecolumnout}% % % Change the page size parameters. We could do this once outside this % routine, in each of @smallbook, @afourpaper, and the default 8.5x11 % format, but then we repeat the same computation. Repeating a couple % of assignments once per index is clearly meaningless for the % execution time, so we may as well do it in one place. % % First we halve the line length, less a little for the gutter between % the columns. We compute the gutter based on the line length, so it % changes automatically with the paper format. The magic constant % below is chosen so that the gutter has the same value (well, +-<1pt) % as it did when we hard-coded it. % % We put the result in a separate register, \doublecolumhsize, so we % can restore it in \pagesofar, after \hsize itself has (potentially) % been clobbered. % \doublecolumnhsize = \hsize \advance\doublecolumnhsize by -.04154\hsize \divide\doublecolumnhsize by 2 \hsize = \doublecolumnhsize % % Double the \vsize as well. (We don't need a separate register here, % since nobody clobbers \vsize.) \vsize = 2\vsize } % The double-column output routine for all double-column pages except % the last. % \def\doublecolumnout{% \splittopskip=\topskip \splitmaxdepth=\maxdepth % Get the available space for the double columns -- the normal % (undoubled) page height minus any material left over from the % previous page. \dimen@ = \vsize \divide\dimen@ by 2 \advance\dimen@ by -\ht\partialpage % % box0 will be the left-hand column, box2 the right. \setbox0=\vsplit255 to\dimen@ \setbox2=\vsplit255 to\dimen@ \onepageout\pagesofar \unvbox255 \penalty\outputpenalty } % % Re-output the contents of the output page -- any previous material, % followed by the two boxes we just split, in box0 and box2. \def\pagesofar{% \unvbox\partialpage % \hsize = \doublecolumnhsize \wd0=\hsize \wd2=\hsize \hbox to\pagewidth{\box0\hfil\box2}% } % % All done with double columns. \def\enddoublecolumns{% % The following penalty ensures that the page builder is exercised % _before_ we change the output routine. This is necessary in the % following situation: % % The last section of the index consists only of a single entry. % Before this section, \pagetotal is less than \pagegoal, so no % break occurs before the last section starts. However, the last % section, consisting of \initial and the single \entry, does not % fit on the page and has to be broken off. Without the following % penalty the page builder will not be exercised until \eject % below, and by that time we'll already have changed the output % routine to the \balancecolumns version, so the next-to-last % double-column page will be processed with \balancecolumns, which % is wrong: The two columns will go to the main vertical list, with % the broken-off section in the recent contributions. As soon as % the output routine finishes, TeX starts reconsidering the page % break. The two columns and the broken-off section both fit on the % page, because the two columns now take up only half of the page % goal. When TeX sees \eject from below which follows the final % section, it invokes the new output routine that we've set after % \balancecolumns below; \onepageout will try to fit the two columns % and the final section into the vbox of \pageheight (see % \pagebody), causing an overfull box. % % Note that glue won't work here, because glue does not exercise the % page builder, unlike penalties (see The TeXbook, pp. 280-281). \penalty0 % \output = {% % Split the last of the double-column material. Leave it on the % current page, no automatic page break. \balancecolumns % % If we end up splitting too much material for the current page, % though, there will be another page break right after this \output % invocation ends. Having called \balancecolumns once, we do not % want to call it again. Therefore, reset \output to its normal % definition right away. (We hope \balancecolumns will never be % called on to balance too much material, but if it is, this makes % the output somewhat more palatable.) \global\output = {\onepageout{\pagecontents\PAGE}}% }% \eject \endgroup % started in \begindoublecolumns % % \pagegoal was set to the doubled \vsize above, since we restarted % the current page. We're now back to normal single-column % typesetting, so reset \pagegoal to the normal \vsize (after the % \endgroup where \vsize got restored). \pagegoal = \vsize } % % Called at the end of the double column material. \def\balancecolumns{% \setbox0 = \vbox{\unvbox255}% like \box255 but more efficient, see p.120. \dimen@ = \ht0 \advance\dimen@ by \topskip \advance\dimen@ by-\baselineskip \divide\dimen@ by 2 % target to split to %debug\message{final 2-column material height=\the\ht0, target=\the\dimen@.}% \splittopskip = \topskip % Loop until we get a decent breakpoint. {% \vbadness = 10000 \loop \global\setbox3 = \copy0 \global\setbox1 = \vsplit3 to \dimen@ \ifdim\ht3>\dimen@ \global\advance\dimen@ by 1pt \repeat }% %debug\message{split to \the\dimen@, column heights: \the\ht1, \the\ht3.}% \setbox0=\vbox to\dimen@{\unvbox1}% \setbox2=\vbox to\dimen@{\unvbox3}% % \pagesofar } \catcode`\@ = \other \message{sectioning,} % Chapters, sections, etc. % \unnumberedno is an oxymoron, of course. But we count the unnumbered % sections so that we can refer to them unambiguously in the pdf % outlines by their "section number". We avoid collisions with chapter % numbers by starting them at 10000. (If a document ever has 10000 % chapters, we're in trouble anyway, I'm sure.) \newcount\unnumberedno \unnumberedno = 10000 \newcount\chapno \newcount\secno \secno=0 \newcount\subsecno \subsecno=0 \newcount\subsubsecno \subsubsecno=0 % This counter is funny since it counts through charcodes of letters A, B, ... \newcount\appendixno \appendixno = `\@ % % \def\appendixletter{\char\the\appendixno} % We do the following ugly conditional instead of the above simple % construct for the sake of pdftex, which needs the actual % letter in the expansion, not just typeset. % \def\appendixletter{% \ifnum\appendixno=`A A% \else\ifnum\appendixno=`B B% \else\ifnum\appendixno=`C C% \else\ifnum\appendixno=`D D% \else\ifnum\appendixno=`E E% \else\ifnum\appendixno=`F F% \else\ifnum\appendixno=`G G% \else\ifnum\appendixno=`H H% \else\ifnum\appendixno=`I I% \else\ifnum\appendixno=`J J% \else\ifnum\appendixno=`K K% \else\ifnum\appendixno=`L L% \else\ifnum\appendixno=`M M% \else\ifnum\appendixno=`N N% \else\ifnum\appendixno=`O O% \else\ifnum\appendixno=`P P% \else\ifnum\appendixno=`Q Q% \else\ifnum\appendixno=`R R% \else\ifnum\appendixno=`S S% \else\ifnum\appendixno=`T T% \else\ifnum\appendixno=`U U% \else\ifnum\appendixno=`V V% \else\ifnum\appendixno=`W W% \else\ifnum\appendixno=`X X% \else\ifnum\appendixno=`Y Y% \else\ifnum\appendixno=`Z Z% % The \the is necessary, despite appearances, because \appendixletter is % expanded while writing the .toc file. \char\appendixno is not % expandable, thus it is written literally, thus all appendixes come out % with the same letter (or @) in the toc without it. \else\char\the\appendixno \fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi \fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi} % Each @chapter defines this as the name of the chapter. % page headings and footings can use it. @section does likewise. % However, they are not reliable, because we don't use marks. \def\thischapter{} \def\thissection{} \newcount\absseclevel % used to calculate proper heading level \newcount\secbase\secbase=0 % @raisesections/@lowersections modify this count % @raisesections: treat @section as chapter, @subsection as section, etc. \def\raisesections{\global\advance\secbase by -1} \let\up=\raisesections % original BFox name % @lowersections: treat @chapter as section, @section as subsection, etc. \def\lowersections{\global\advance\secbase by 1} \let\down=\lowersections % original BFox name % we only have subsub. \chardef\maxseclevel = 3 % % A numbered section within an unnumbered changes to unnumbered too. % To achive this, remember the "biggest" unnum. sec. we are currently in: \chardef\unmlevel = \maxseclevel % % Trace whether the current chapter is an appendix or not: % \chapheadtype is "N" or "A", unnumbered chapters are ignored. \def\chapheadtype{N} % Choose a heading macro % #1 is heading type % #2 is heading level % #3 is text for heading \def\genhead#1#2#3{% % Compute the abs. sec. level: \absseclevel=#2 \advance\absseclevel by \secbase % Make sure \absseclevel doesn't fall outside the range: \ifnum \absseclevel < 0 \absseclevel = 0 \else \ifnum \absseclevel > 3 \absseclevel = 3 \fi \fi % The heading type: \def\headtype{#1}% \if \headtype U% \ifnum \absseclevel < \unmlevel \chardef\unmlevel = \absseclevel \fi \else % Check for appendix sections: \ifnum \absseclevel = 0 \edef\chapheadtype{\headtype}% \else \if \headtype A\if \chapheadtype N% \errmessage{@appendix... within a non-appendix chapter}% \fi\fi \fi % Check for numbered within unnumbered: \ifnum \absseclevel > \unmlevel \def\headtype{U}% \else \chardef\unmlevel = 3 \fi \fi % Now print the heading: \if \headtype U% \ifcase\absseclevel \unnumberedzzz{#3}% \or \unnumberedseczzz{#3}% \or \unnumberedsubseczzz{#3}% \or \unnumberedsubsubseczzz{#3}% \fi \else \if \headtype A% \ifcase\absseclevel \appendixzzz{#3}% \or \appendixsectionzzz{#3}% \or \appendixsubseczzz{#3}% \or \appendixsubsubseczzz{#3}% \fi \else \ifcase\absseclevel \chapterzzz{#3}% \or \seczzz{#3}% \or \numberedsubseczzz{#3}% \or \numberedsubsubseczzz{#3}% \fi \fi \fi \suppressfirstparagraphindent } % an interface: \def\numhead{\genhead N} \def\apphead{\genhead A} \def\unnmhead{\genhead U} % @chapter, @appendix, @unnumbered. Increment top-level counter, reset % all lower-level sectioning counters to zero. % % Also set \chaplevelprefix, which we prepend to @float sequence numbers % (e.g., figures), q.v. By default (before any chapter), that is empty. \let\chaplevelprefix = \empty % \outer\parseargdef\chapter{\numhead0{#1}} % normally numhead0 calls chapterzzz \def\chapterzzz#1{% % section resetting is \global in case the chapter is in a group, such % as an @include file. \global\secno=0 \global\subsecno=0 \global\subsubsecno=0 \global\advance\chapno by 1 % % Used for \float. \gdef\chaplevelprefix{\the\chapno.}% \resetallfloatnos % \message{\putwordChapter\space \the\chapno}% % % Write the actual heading. \chapmacro{#1}{Ynumbered}{\the\chapno}% % % So @section and the like are numbered underneath this chapter. \global\let\section = \numberedsec \global\let\subsection = \numberedsubsec \global\let\subsubsection = \numberedsubsubsec } \outer\parseargdef\appendix{\apphead0{#1}} % normally apphead0 calls appendixzzz \def\appendixzzz#1{% \global\secno=0 \global\subsecno=0 \global\subsubsecno=0 \global\advance\appendixno by 1 \gdef\chaplevelprefix{\appendixletter.}% \resetallfloatnos % \def\appendixnum{\putwordAppendix\space \appendixletter}% \message{\appendixnum}% % \chapmacro{#1}{Yappendix}{\appendixletter}% % \global\let\section = \appendixsec \global\let\subsection = \appendixsubsec \global\let\subsubsection = \appendixsubsubsec } \outer\parseargdef\unnumbered{\unnmhead0{#1}} % normally unnmhead0 calls unnumberedzzz \def\unnumberedzzz#1{% \global\secno=0 \global\subsecno=0 \global\subsubsecno=0 \global\advance\unnumberedno by 1 % % Since an unnumbered has no number, no prefix for figures. \global\let\chaplevelprefix = \empty \resetallfloatnos % % This used to be simply \message{#1}, but TeX fully expands the % argument to \message. Therefore, if #1 contained @-commands, TeX % expanded them. For example, in `@unnumbered The @cite{Book}', TeX % expanded @cite (which turns out to cause errors because \cite is meant % to be executed, not expanded). % % Anyway, we don't want the fully-expanded definition of @cite to appear % as a result of the \message, we just want `@cite' itself. We use % \the to achieve this: TeX expands \the only once, % simply yielding the contents of . (We also do this for % the toc entries.) \toks0 = {#1}% \message{(\the\toks0)}% % \chapmacro{#1}{Ynothing}{\the\unnumberedno}% % \global\let\section = \unnumberedsec \global\let\subsection = \unnumberedsubsec \global\let\subsubsection = \unnumberedsubsubsec } % @centerchap is like @unnumbered, but the heading is centered. \outer\parseargdef\centerchap{% % Well, we could do the following in a group, but that would break % an assumption that \chapmacro is called at the outermost level. % Thus we are safer this way: --kasal, 24feb04 \let\centerparametersmaybe = \centerparameters \unnmhead0{#1}% \let\centerparametersmaybe = \relax } % @top is like @unnumbered. \let\top\unnumbered % Sections. \outer\parseargdef\numberedsec{\numhead1{#1}} % normally calls seczzz \def\seczzz#1{% \global\subsecno=0 \global\subsubsecno=0 \global\advance\secno by 1 \sectionheading{#1}{sec}{Ynumbered}{\the\chapno.\the\secno}% } \outer\parseargdef\appendixsection{\apphead1{#1}} % normally calls appendixsectionzzz \def\appendixsectionzzz#1{% \global\subsecno=0 \global\subsubsecno=0 \global\advance\secno by 1 \sectionheading{#1}{sec}{Yappendix}{\appendixletter.\the\secno}% } \let\appendixsec\appendixsection \outer\parseargdef\unnumberedsec{\unnmhead1{#1}} % normally calls unnumberedseczzz \def\unnumberedseczzz#1{% \global\subsecno=0 \global\subsubsecno=0 \global\advance\secno by 1 \sectionheading{#1}{sec}{Ynothing}{\the\unnumberedno.\the\secno}% } % Subsections. \outer\parseargdef\numberedsubsec{\numhead2{#1}} % normally calls numberedsubseczzz \def\numberedsubseczzz#1{% \global\subsubsecno=0 \global\advance\subsecno by 1 \sectionheading{#1}{subsec}{Ynumbered}{\the\chapno.\the\secno.\the\subsecno}% } \outer\parseargdef\appendixsubsec{\apphead2{#1}} % normally calls appendixsubseczzz \def\appendixsubseczzz#1{% \global\subsubsecno=0 \global\advance\subsecno by 1 \sectionheading{#1}{subsec}{Yappendix}% {\appendixletter.\the\secno.\the\subsecno}% } \outer\parseargdef\unnumberedsubsec{\unnmhead2{#1}} %normally calls unnumberedsubseczzz \def\unnumberedsubseczzz#1{% \global\subsubsecno=0 \global\advance\subsecno by 1 \sectionheading{#1}{subsec}{Ynothing}% {\the\unnumberedno.\the\secno.\the\subsecno}% } % Subsubsections. \outer\parseargdef\numberedsubsubsec{\numhead3{#1}} % normally numberedsubsubseczzz \def\numberedsubsubseczzz#1{% \global\advance\subsubsecno by 1 \sectionheading{#1}{subsubsec}{Ynumbered}% {\the\chapno.\the\secno.\the\subsecno.\the\subsubsecno}% } \outer\parseargdef\appendixsubsubsec{\apphead3{#1}} % normally appendixsubsubseczzz \def\appendixsubsubseczzz#1{% \global\advance\subsubsecno by 1 \sectionheading{#1}{subsubsec}{Yappendix}% {\appendixletter.\the\secno.\the\subsecno.\the\subsubsecno}% } \outer\parseargdef\unnumberedsubsubsec{\unnmhead3{#1}} %normally unnumberedsubsubseczzz \def\unnumberedsubsubseczzz#1{% \global\advance\subsubsecno by 1 \sectionheading{#1}{subsubsec}{Ynothing}% {\the\unnumberedno.\the\secno.\the\subsecno.\the\subsubsecno}% } % These macros control what the section commands do, according % to what kind of chapter we are in (ordinary, appendix, or unnumbered). % Define them by default for a numbered chapter. \let\section = \numberedsec \let\subsection = \numberedsubsec \let\subsubsection = \numberedsubsubsec % Define @majorheading, @heading and @subheading % NOTE on use of \vbox for chapter headings, section headings, and such: % 1) We use \vbox rather than the earlier \line to permit % overlong headings to fold. % 2) \hyphenpenalty is set to 10000 because hyphenation in a % heading is obnoxious; this forbids it. % 3) Likewise, headings look best if no \parindent is used, and % if justification is not attempted. Hence \raggedright. \def\majorheading{% {\advance\chapheadingskip by 10pt \chapbreak }% \parsearg\chapheadingzzz } \def\chapheading{\chapbreak \parsearg\chapheadingzzz} \def\chapheadingzzz#1{% {\chapfonts \vbox{\hyphenpenalty=10000\tolerance=5000 \parindent=0pt\raggedright \rm #1\hfill}}% \bigskip \par\penalty 200\relax \suppressfirstparagraphindent } % @heading, @subheading, @subsubheading. \parseargdef\heading{\sectionheading{#1}{sec}{Yomitfromtoc}{} \suppressfirstparagraphindent} \parseargdef\subheading{\sectionheading{#1}{subsec}{Yomitfromtoc}{} \suppressfirstparagraphindent} \parseargdef\subsubheading{\sectionheading{#1}{subsubsec}{Yomitfromtoc}{} \suppressfirstparagraphindent} % These macros generate a chapter, section, etc. heading only % (including whitespace, linebreaking, etc. around it), % given all the information in convenient, parsed form. %%% Args are the skip and penalty (usually negative) \def\dobreak#1#2{\par\ifdim\lastskip<#1\removelastskip\penalty#2\vskip#1\fi} %%% Define plain chapter starts, and page on/off switching for it % Parameter controlling skip before chapter headings (if needed) \newskip\chapheadingskip \def\chapbreak{\dobreak \chapheadingskip {-4000}} \def\chappager{\par\vfill\supereject} \def\chapoddpage{\chappager \ifodd\pageno \else \hbox to 0pt{} \chappager\fi} \def\setchapternewpage #1 {\csname CHAPPAG#1\endcsname} \def\CHAPPAGoff{% \global\let\contentsalignmacro = \chappager \global\let\pchapsepmacro=\chapbreak \global\let\pagealignmacro=\chappager} \def\CHAPPAGon{% \global\let\contentsalignmacro = \chappager \global\let\pchapsepmacro=\chappager \global\let\pagealignmacro=\chappager \global\def\HEADINGSon{\HEADINGSsingle}} \def\CHAPPAGodd{% \global\let\contentsalignmacro = \chapoddpage \global\let\pchapsepmacro=\chapoddpage \global\let\pagealignmacro=\chapoddpage \global\def\HEADINGSon{\HEADINGSdouble}} \CHAPPAGon % Chapter opening. % % #1 is the text, #2 is the section type (Ynumbered, Ynothing, % Yappendix, Yomitfromtoc), #3 the chapter number. % % To test against our argument. \def\Ynothingkeyword{Ynothing} \def\Yomitfromtockeyword{Yomitfromtoc} \def\Yappendixkeyword{Yappendix} % \def\chapmacro#1#2#3{% \pchapsepmacro {% \chapfonts \rm % % Have to define \thissection before calling \donoderef, because the % xref code eventually uses it. On the other hand, it has to be called % after \pchapsepmacro, or the headline will change too soon. \gdef\thissection{#1}% \gdef\thischaptername{#1}% % % Only insert the separating space if we have a chapter/appendix % number, and don't print the unnumbered ``number''. \def\temptype{#2}% \ifx\temptype\Ynothingkeyword \setbox0 = \hbox{}% \def\toctype{unnchap}% \gdef\thischapternum{}% \gdef\thischapter{#1}% \else\ifx\temptype\Yomitfromtockeyword \setbox0 = \hbox{}% contents like unnumbered, but no toc entry \def\toctype{omit}% \gdef\thischapternum{}% \gdef\thischapter{}% \else\ifx\temptype\Yappendixkeyword \setbox0 = \hbox{\putwordAppendix{} #3\enspace}% \def\toctype{app}% \xdef\thischapternum{\appendixletter}% % We don't substitute the actual chapter name into \thischapter % because we don't want its macros evaluated now. And we don't % use \thissection because that changes with each section. % \xdef\thischapter{\putwordAppendix{} \appendixletter: \noexpand\thischaptername}% \else \setbox0 = \hbox{#3\enspace}% \def\toctype{numchap}% \xdef\thischapternum{\the\chapno}% \xdef\thischapter{\putwordChapter{} \the\chapno: \noexpand\thischaptername}% \fi\fi\fi % % Write the toc entry for this chapter. Must come before the % \donoderef, because we include the current node name in the toc % entry, and \donoderef resets it to empty. \writetocentry{\toctype}{#1}{#3}% % % For pdftex, we have to write out the node definition (aka, make % the pdfdest) after any page break, but before the actual text has % been typeset. If the destination for the pdf outline is after the % text, then jumping from the outline may wind up with the text not % being visible, for instance under high magnification. \donoderef{#2}% % % Typeset the actual heading. \vbox{\hyphenpenalty=10000 \tolerance=5000 \parindent=0pt \raggedright \hangindent=\wd0 \centerparametersmaybe \unhbox0 #1\par}% }% \nobreak\bigskip % no page break after a chapter title \nobreak } % @centerchap -- centered and unnumbered. \let\centerparametersmaybe = \relax \def\centerparameters{% \advance\rightskip by 3\rightskip \leftskip = \rightskip \parfillskip = 0pt } % I don't think this chapter style is supported any more, so I'm not % updating it with the new noderef stuff. We'll see. --karl, 11aug03. % \def\setchapterstyle #1 {\csname CHAPF#1\endcsname} % \def\unnchfopen #1{% \chapoddpage {\chapfonts \vbox{\hyphenpenalty=10000\tolerance=5000 \parindent=0pt\raggedright \rm #1\hfill}}\bigskip \par\nobreak } \def\chfopen #1#2{\chapoddpage {\chapfonts \vbox to 3in{\vfil \hbox to\hsize{\hfil #2} \hbox to\hsize{\hfil #1} \vfil}}% \par\penalty 5000 % } \def\centerchfopen #1{% \chapoddpage {\chapfonts \vbox{\hyphenpenalty=10000\tolerance=5000 \parindent=0pt \hfill {\rm #1}\hfill}}\bigskip \par\nobreak } \def\CHAPFopen{% \global\let\chapmacro=\chfopen \global\let\centerchapmacro=\centerchfopen} % Section titles. These macros combine the section number parts and % call the generic \sectionheading to do the printing. % \newskip\secheadingskip \def\secheadingbreak{\dobreak \secheadingskip{-1000}} % Subsection titles. \newskip\subsecheadingskip \def\subsecheadingbreak{\dobreak \subsecheadingskip{-500}} % Subsubsection titles. \def\subsubsecheadingskip{\subsecheadingskip} \def\subsubsecheadingbreak{\subsecheadingbreak} % Print any size, any type, section title. % % #1 is the text, #2 is the section level (sec/subsec/subsubsec), #3 is % the section type for xrefs (Ynumbered, Ynothing, Yappendix), #4 is the % section number. % \def\sectionheading#1#2#3#4{% {% % Switch to the right set of fonts. \csname #2fonts\endcsname \rm % % Insert space above the heading. \csname #2headingbreak\endcsname % % Only insert the space after the number if we have a section number. \def\sectionlevel{#2}% \def\temptype{#3}% % \ifx\temptype\Ynothingkeyword \setbox0 = \hbox{}% \def\toctype{unn}% \gdef\thissection{#1}% \else\ifx\temptype\Yomitfromtockeyword % for @headings -- no section number, don't include in toc, % and don't redefine \thissection. \setbox0 = \hbox{}% \def\toctype{omit}% \let\sectionlevel=\empty \else\ifx\temptype\Yappendixkeyword \setbox0 = \hbox{#4\enspace}% \def\toctype{app}% \gdef\thissection{#1}% \else \setbox0 = \hbox{#4\enspace}% \def\toctype{num}% \gdef\thissection{#1}% \fi\fi\fi % % Write the toc entry (before \donoderef). See comments in \chapmacro. \writetocentry{\toctype\sectionlevel}{#1}{#4}% % % Write the node reference (= pdf destination for pdftex). % Again, see comments in \chapmacro. \donoderef{#3}% % % Interline glue will be inserted when the vbox is completed. % That glue will be a valid breakpoint for the page, since it'll be % preceded by a whatsit (usually from the \donoderef, or from the % \writetocentry if there was no node). We don't want to allow that % break, since then the whatsits could end up on page n while the % section is on page n+1, thus toc/etc. are wrong. Debian bug 276000. \nobreak % % Output the actual section heading. \vbox{\hyphenpenalty=10000 \tolerance=5000 \parindent=0pt \raggedright \hangindent=\wd0 % zero if no section number \unhbox0 #1}% }% % Add extra space after the heading -- half of whatever came above it. % Don't allow stretch, though. \kern .5 \csname #2headingskip\endcsname % % Do not let the kern be a potential breakpoint, as it would be if it % was followed by glue. \nobreak % % We'll almost certainly start a paragraph next, so don't let that % glue accumulate. (Not a breakpoint because it's preceded by a % discardable item.) \vskip-\parskip % % This is purely so the last item on the list is a known \penalty > % 10000. This is so \startdefun can avoid allowing breakpoints after % section headings. Otherwise, it would insert a valid breakpoint between: % % @section sec-whatever % @deffn def-whatever \penalty 10001 } \message{toc,} % Table of contents. \newwrite\tocfile % Write an entry to the toc file, opening it if necessary. % Called from @chapter, etc. % % Example usage: \writetocentry{sec}{Section Name}{\the\chapno.\the\secno} % We append the current node name (if any) and page number as additional % arguments for the \{chap,sec,...}entry macros which will eventually % read this. The node name is used in the pdf outlines as the % destination to jump to. % % We open the .toc file for writing here instead of at @setfilename (or % any other fixed time) so that @contents can be anywhere in the document. % But if #1 is `omit', then we don't do anything. This is used for the % table of contents chapter openings themselves. % \newif\iftocfileopened \def\omitkeyword{omit}% % \def\writetocentry#1#2#3{% \edef\writetoctype{#1}% \ifx\writetoctype\omitkeyword \else \iftocfileopened\else \immediate\openout\tocfile = \jobname.toc \global\tocfileopenedtrue \fi % \iflinks {\atdummies \edef\temp{% \write\tocfile{@#1entry{#2}{#3}{\lastnode}{\noexpand\folio}}}% \temp }% \fi \fi % % Tell \shipout to create a pdf destination on each page, if we're % writing pdf. These are used in the table of contents. We can't % just write one on every page because the title pages are numbered % 1 and 2 (the page numbers aren't printed), and so are the first % two pages of the document. Thus, we'd have two destinations named % `1', and two named `2'. \ifpdf \global\pdfmakepagedesttrue \fi } % These characters do not print properly in the Computer Modern roman % fonts, so we must take special care. This is more or less redundant % with the Texinfo input format setup at the end of this file. % \def\activecatcodes{% \catcode`\"=\active \catcode`\$=\active \catcode`\<=\active \catcode`\>=\active \catcode`\\=\active \catcode`\^=\active \catcode`\_=\active \catcode`\|=\active \catcode`\~=\active } % Read the toc file, which is essentially Texinfo input. \def\readtocfile{% \setupdatafile \activecatcodes \input \jobname.toc } \newskip\contentsrightmargin \contentsrightmargin=1in \newcount\savepageno \newcount\lastnegativepageno \lastnegativepageno = -1 % Prepare to read what we've written to \tocfile. % \def\startcontents#1{% % If @setchapternewpage on, and @headings double, the contents should % start on an odd page, unlike chapters. Thus, we maintain % \contentsalignmacro in parallel with \pagealignmacro. % From: Torbjorn Granlund \contentsalignmacro \immediate\closeout\tocfile % % Don't need to put `Contents' or `Short Contents' in the headline. % It is abundantly clear what they are. \def\thischapter{}% \chapmacro{#1}{Yomitfromtoc}{}% % \savepageno = \pageno \begingroup % Set up to handle contents files properly. \raggedbottom % Worry more about breakpoints than the bottom. \advance\hsize by -\contentsrightmargin % Don't use the full line length. % % Roman numerals for page numbers. \ifnum \pageno>0 \global\pageno = \lastnegativepageno \fi } % Normal (long) toc. \def\contents{% \startcontents{\putwordTOC}% \openin 1 \jobname.toc \ifeof 1 \else \readtocfile \fi \vfill \eject \contentsalignmacro % in case @setchapternewpage odd is in effect \ifeof 1 \else \pdfmakeoutlines \fi \closein 1 \endgroup \lastnegativepageno = \pageno \global\pageno = \savepageno } % And just the chapters. \def\summarycontents{% \startcontents{\putwordShortTOC}% % \let\numchapentry = \shortchapentry \let\appentry = \shortchapentry \let\unnchapentry = \shortunnchapentry % We want a true roman here for the page numbers. \secfonts \let\rm=\shortcontrm \let\bf=\shortcontbf \let\sl=\shortcontsl \let\tt=\shortconttt \rm \hyphenpenalty = 10000 \advance\baselineskip by 1pt % Open it up a little. \def\numsecentry##1##2##3##4{} \let\appsecentry = \numsecentry \let\unnsecentry = \numsecentry \let\numsubsecentry = \numsecentry \let\appsubsecentry = \numsecentry \let\unnsubsecentry = \numsecentry \let\numsubsubsecentry = \numsecentry \let\appsubsubsecentry = \numsecentry \let\unnsubsubsecentry = \numsecentry \openin 1 \jobname.toc \ifeof 1 \else \readtocfile \fi \closein 1 \vfill \eject \contentsalignmacro % in case @setchapternewpage odd is in effect \endgroup \lastnegativepageno = \pageno \global\pageno = \savepageno } \let\shortcontents = \summarycontents % Typeset the label for a chapter or appendix for the short contents. % The arg is, e.g., `A' for an appendix, or `3' for a chapter. % \def\shortchaplabel#1{% % This space should be enough, since a single number is .5em, and the % widest letter (M) is 1em, at least in the Computer Modern fonts. % But use \hss just in case. % (This space doesn't include the extra space that gets added after % the label; that gets put in by \shortchapentry above.) % % We'd like to right-justify chapter numbers, but that looks strange % with appendix letters. And right-justifying numbers and % left-justifying letters looks strange when there is less than 10 % chapters. Have to read the whole toc once to know how many chapters % there are before deciding ... \hbox to 1em{#1\hss}% } % These macros generate individual entries in the table of contents. % The first argument is the chapter or section name. % The last argument is the page number. % The arguments in between are the chapter number, section number, ... % Chapters, in the main contents. \def\numchapentry#1#2#3#4{\dochapentry{#2\labelspace#1}{#4}} % % Chapters, in the short toc. % See comments in \dochapentry re vbox and related settings. \def\shortchapentry#1#2#3#4{% \tocentry{\shortchaplabel{#2}\labelspace #1}{\doshortpageno\bgroup#4\egroup}% } % Appendices, in the main contents. % Need the word Appendix, and a fixed-size box. % \def\appendixbox#1{% % We use M since it's probably the widest letter. \setbox0 = \hbox{\putwordAppendix{} M}% \hbox to \wd0{\putwordAppendix{} #1\hss}} % \def\appentry#1#2#3#4{\dochapentry{\appendixbox{#2}\labelspace#1}{#4}} % Unnumbered chapters. \def\unnchapentry#1#2#3#4{\dochapentry{#1}{#4}} \def\shortunnchapentry#1#2#3#4{\tocentry{#1}{\doshortpageno\bgroup#4\egroup}} % Sections. \def\numsecentry#1#2#3#4{\dosecentry{#2\labelspace#1}{#4}} \let\appsecentry=\numsecentry \def\unnsecentry#1#2#3#4{\dosecentry{#1}{#4}} % Subsections. \def\numsubsecentry#1#2#3#4{\dosubsecentry{#2\labelspace#1}{#4}} \let\appsubsecentry=\numsubsecentry \def\unnsubsecentry#1#2#3#4{\dosubsecentry{#1}{#4}} % And subsubsections. \def\numsubsubsecentry#1#2#3#4{\dosubsubsecentry{#2\labelspace#1}{#4}} \let\appsubsubsecentry=\numsubsubsecentry \def\unnsubsubsecentry#1#2#3#4{\dosubsubsecentry{#1}{#4}} % This parameter controls the indentation of the various levels. % Same as \defaultparindent. \newdimen\tocindent \tocindent = 15pt % Now for the actual typesetting. In all these, #1 is the text and #2 is the % page number. % % If the toc has to be broken over pages, we want it to be at chapters % if at all possible; hence the \penalty. \def\dochapentry#1#2{% \penalty-300 \vskip1\baselineskip plus.33\baselineskip minus.25\baselineskip \begingroup \chapentryfonts \tocentry{#1}{\dopageno\bgroup#2\egroup}% \endgroup \nobreak\vskip .25\baselineskip plus.1\baselineskip } \def\dosecentry#1#2{\begingroup \secentryfonts \leftskip=\tocindent \tocentry{#1}{\dopageno\bgroup#2\egroup}% \endgroup} \def\dosubsecentry#1#2{\begingroup \subsecentryfonts \leftskip=2\tocindent \tocentry{#1}{\dopageno\bgroup#2\egroup}% \endgroup} \def\dosubsubsecentry#1#2{\begingroup \subsubsecentryfonts \leftskip=3\tocindent \tocentry{#1}{\dopageno\bgroup#2\egroup}% \endgroup} % We use the same \entry macro as for the index entries. \let\tocentry = \entry % Space between chapter (or whatever) number and the title. \def\labelspace{\hskip1em \relax} \def\dopageno#1{{\rm #1}} \def\doshortpageno#1{{\rm #1}} \def\chapentryfonts{\secfonts \rm} \def\secentryfonts{\textfonts} \def\subsecentryfonts{\textfonts} \def\subsubsecentryfonts{\textfonts} \message{environments,} % @foo ... @end foo. % @point{}, @result{}, @expansion{}, @print{}, @equiv{}. % % Since these characters are used in examples, it should be an even number of % \tt widths. Each \tt character is 1en, so two makes it 1em. % \def\point{$\star$} \def\result{\leavevmode\raise.15ex\hbox to 1em{\hfil$\Rightarrow$\hfil}} \def\expansion{\leavevmode\raise.1ex\hbox to 1em{\hfil$\mapsto$\hfil}} \def\print{\leavevmode\lower.1ex\hbox to 1em{\hfil$\dashv$\hfil}} \def\equiv{\leavevmode\lower.1ex\hbox to 1em{\hfil$\ptexequiv$\hfil}} % The @error{} command. % Adapted from the TeXbook's \boxit. % \newbox\errorbox % {\tentt \global\dimen0 = 3em}% Width of the box. \dimen2 = .55pt % Thickness of rules % The text. (`r' is open on the right, `e' somewhat less so on the left.) \setbox0 = \hbox{\kern-.75pt \reducedsf error\kern-1.5pt} % \setbox\errorbox=\hbox to \dimen0{\hfil \hsize = \dimen0 \advance\hsize by -5.8pt % Space to left+right. \advance\hsize by -2\dimen2 % Rules. \vbox{% \hrule height\dimen2 \hbox{\vrule width\dimen2 \kern3pt % Space to left of text. \vtop{\kern2.4pt \box0 \kern2.4pt}% Space above/below. \kern3pt\vrule width\dimen2}% Space to right. \hrule height\dimen2} \hfil} % \def\error{\leavevmode\lower.7ex\copy\errorbox} % @tex ... @end tex escapes into raw Tex temporarily. % One exception: @ is still an escape character, so that @end tex works. % But \@ or @@ will get a plain tex @ character. \envdef\tex{% \catcode `\\=0 \catcode `\{=1 \catcode `\}=2 \catcode `\$=3 \catcode `\&=4 \catcode `\#=6 \catcode `\^=7 \catcode `\_=8 \catcode `\~=\active \let~=\tie \catcode `\%=14 \catcode `\+=\other \catcode `\"=\other \catcode `\|=\other \catcode `\<=\other \catcode `\>=\other \escapechar=`\\ % \let\b=\ptexb \let\bullet=\ptexbullet \let\c=\ptexc \let\,=\ptexcomma \let\.=\ptexdot \let\dots=\ptexdots \let\equiv=\ptexequiv \let\!=\ptexexclam \let\i=\ptexi \let\indent=\ptexindent \let\noindent=\ptexnoindent \let\{=\ptexlbrace \let\+=\tabalign \let\}=\ptexrbrace \let\/=\ptexslash \let\*=\ptexstar \let\t=\ptext \let\frenchspacing=\plainfrenchspacing % \def\endldots{\mathinner{\ldots\ldots\ldots\ldots}}% \def\enddots{\relax\ifmmode\endldots\else$\mathsurround=0pt \endldots\,$\fi}% \def\@{@}% } % There is no need to define \Etex. % Define @lisp ... @end lisp. % @lisp environment forms a group so it can rebind things, % including the definition of @end lisp (which normally is erroneous). % Amount to narrow the margins by for @lisp. \newskip\lispnarrowing \lispnarrowing=0.4in % This is the definition that ^^M gets inside @lisp, @example, and other % such environments. \null is better than a space, since it doesn't % have any width. \def\lisppar{\null\endgraf} % This space is always present above and below environments. \newskip\envskipamount \envskipamount = 0pt % Make spacing and below environment symmetrical. We use \parskip here % to help in doing that, since in @example-like environments \parskip % is reset to zero; thus the \afterenvbreak inserts no space -- but the % start of the next paragraph will insert \parskip. % \def\aboveenvbreak{{% % =10000 instead of <10000 because of a special case in \itemzzz and % \sectionheading, q.v. \ifnum \lastpenalty=10000 \else \advance\envskipamount by \parskip \endgraf \ifdim\lastskip<\envskipamount \removelastskip % it's not a good place to break if the last penalty was \nobreak % or better ... \ifnum\lastpenalty<10000 \penalty-50 \fi \vskip\envskipamount \fi \fi }} \let\afterenvbreak = \aboveenvbreak % \nonarrowing is a flag. If "set", @lisp etc don't narrow margins; it will % also clear it, so that its embedded environments do the narrowing again. \let\nonarrowing=\relax % @cartouche ... @end cartouche: draw rectangle w/rounded corners around % environment contents. \font\circle=lcircle10 \newdimen\circthick \newdimen\cartouter\newdimen\cartinner \newskip\normbskip\newskip\normpskip\newskip\normlskip \circthick=\fontdimen8\circle % \def\ctl{{\circle\char'013\hskip -6pt}}% 6pt from pl file: 1/2charwidth \def\ctr{{\hskip 6pt\circle\char'010}} \def\cbl{{\circle\char'012\hskip -6pt}} \def\cbr{{\hskip 6pt\circle\char'011}} \def\carttop{\hbox to \cartouter{\hskip\lskip \ctl\leaders\hrule height\circthick\hfil\ctr \hskip\rskip}} \def\cartbot{\hbox to \cartouter{\hskip\lskip \cbl\leaders\hrule height\circthick\hfil\cbr \hskip\rskip}} % \newskip\lskip\newskip\rskip \envdef\cartouche{% \ifhmode\par\fi % can't be in the midst of a paragraph. \startsavinginserts \lskip=\leftskip \rskip=\rightskip \leftskip=0pt\rightskip=0pt % we want these *outside*. \cartinner=\hsize \advance\cartinner by-\lskip \advance\cartinner by-\rskip \cartouter=\hsize \advance\cartouter by 18.4pt % allow for 3pt kerns on either % side, and for 6pt waste from % each corner char, and rule thickness \normbskip=\baselineskip \normpskip=\parskip \normlskip=\lineskip % Flag to tell @lisp, etc., not to narrow margin. \let\nonarrowing = t% \vbox\bgroup \baselineskip=0pt\parskip=0pt\lineskip=0pt \carttop \hbox\bgroup \hskip\lskip \vrule\kern3pt \vbox\bgroup \kern3pt \hsize=\cartinner \baselineskip=\normbskip \lineskip=\normlskip \parskip=\normpskip \vskip -\parskip \comment % For explanation, see the end of \def\group. } \def\Ecartouche{% \ifhmode\par\fi \kern3pt \egroup \kern3pt\vrule \hskip\rskip \egroup \cartbot \egroup \checkinserts } % This macro is called at the beginning of all the @example variants, % inside a group. \def\nonfillstart{% \aboveenvbreak \hfuzz = 12pt % Don't be fussy \sepspaces % Make spaces be word-separators rather than space tokens. \let\par = \lisppar % don't ignore blank lines \obeylines % each line of input is a line of output \parskip = 0pt \parindent = 0pt \emergencystretch = 0pt % don't try to avoid overfull boxes \ifx\nonarrowing\relax \advance \leftskip by \lispnarrowing \exdentamount=\lispnarrowing \else \let\nonarrowing = \relax \fi \let\exdent=\nofillexdent } % If you want all examples etc. small: @set dispenvsize small. % If you want even small examples the full size: @set dispenvsize nosmall. % This affects the following displayed environments: % @example, @display, @format, @lisp % \def\smallword{small} \def\nosmallword{nosmall} \let\SETdispenvsize\relax \def\setnormaldispenv{% \ifx\SETdispenvsize\smallword % end paragraph for sake of leading, in case document has no blank % line. This is redundant with what happens in \aboveenvbreak, but % we need to do it before changing the fonts, and it's inconvenient % to change the fonts afterward. \ifnum \lastpenalty=10000 \else \endgraf \fi \smallexamplefonts \rm \fi } \def\setsmalldispenv{% \ifx\SETdispenvsize\nosmallword \else \ifnum \lastpenalty=10000 \else \endgraf \fi \smallexamplefonts \rm \fi } % We often define two environments, @foo and @smallfoo. % Let's do it by one command: \def\makedispenv #1#2{ \expandafter\envdef\csname#1\endcsname {\setnormaldispenv #2} \expandafter\envdef\csname small#1\endcsname {\setsmalldispenv #2} \expandafter\let\csname E#1\endcsname \afterenvbreak \expandafter\let\csname Esmall#1\endcsname \afterenvbreak } % Define two synonyms: \def\maketwodispenvs #1#2#3{ \makedispenv{#1}{#3} \makedispenv{#2}{#3} } % @lisp: indented, narrowed, typewriter font; @example: same as @lisp. % % @smallexample and @smalllisp: use smaller fonts. % Originally contributed by Pavel@xerox. % \maketwodispenvs {lisp}{example}{% \nonfillstart \tt\quoteexpand \let\kbdfont = \kbdexamplefont % Allow @kbd to do something special. \gobble % eat return } % @display/@smalldisplay: same as @lisp except keep current font. % \makedispenv {display}{% \nonfillstart \gobble } % @format/@smallformat: same as @display except don't narrow margins. % \makedispenv{format}{% \let\nonarrowing = t% \nonfillstart \gobble } % @flushleft: same as @format, but doesn't obey \SETdispenvsize. \envdef\flushleft{% \let\nonarrowing = t% \nonfillstart \gobble } \let\Eflushleft = \afterenvbreak % @flushright. % \envdef\flushright{% \let\nonarrowing = t% \nonfillstart \advance\leftskip by 0pt plus 1fill \gobble } \let\Eflushright = \afterenvbreak % @quotation does normal linebreaking (hence we can't use \nonfillstart) % and narrows the margins. We keep \parskip nonzero in general, since % we're doing normal filling. So, when using \aboveenvbreak and % \afterenvbreak, temporarily make \parskip 0. % \envdef\quotation{% {\parskip=0pt \aboveenvbreak}% because \aboveenvbreak inserts \parskip \parindent=0pt % % @cartouche defines \nonarrowing to inhibit narrowing at next level down. \ifx\nonarrowing\relax \advance\leftskip by \lispnarrowing \advance\rightskip by \lispnarrowing \exdentamount = \lispnarrowing \else \let\nonarrowing = \relax \fi \parsearg\quotationlabel } % We have retained a nonzero parskip for the environment, since we're % doing normal filling. % \def\Equotation{% \par \ifx\quotationauthor\undefined\else % indent a bit. \leftline{\kern 2\leftskip \sl ---\quotationauthor}% \fi {\parskip=0pt \afterenvbreak}% } % If we're given an argument, typeset it in bold with a colon after. \def\quotationlabel#1{% \def\temp{#1}% \ifx\temp\empty \else {\bf #1: }% \fi } % LaTeX-like @verbatim...@end verbatim and @verb{...} % If we want to allow any as delimiter, % we need the curly braces so that makeinfo sees the @verb command, eg: % `@verbx...x' would look like the '@verbx' command. --janneke@gnu.org % % [Knuth]: Donald Ervin Knuth, 1996. The TeXbook. % % [Knuth] p.344; only we need to do the other characters Texinfo sets % active too. Otherwise, they get lost as the first character on a % verbatim line. \def\dospecials{% \do\ \do\\\do\{\do\}\do\$\do\&% \do\#\do\^\do\^^K\do\_\do\^^A\do\%\do\~% \do\<\do\>\do\|\do\@\do+\do\"% } % % [Knuth] p. 380 \def\uncatcodespecials{% \def\do##1{\catcode`##1=\other}\dospecials} % % [Knuth] pp. 380,381,391 % Disable Spanish ligatures ?` and !` of \tt font \begingroup \catcode`\`=\active\gdef`{\relax\lq} \endgroup % % Setup for the @verb command. % % Eight spaces for a tab \begingroup \catcode`\^^I=\active \gdef\tabeightspaces{\catcode`\^^I=\active\def^^I{\ \ \ \ \ \ \ \ }} \endgroup % \def\setupverb{% \tt % easiest (and conventionally used) font for verbatim \def\par{\leavevmode\endgraf}% \catcode`\`=\active \tabeightspaces % Respect line breaks, % print special symbols as themselves, and % make each space count % must do in this order: \obeylines \uncatcodespecials \sepspaces } % Setup for the @verbatim environment % % Real tab expansion \newdimen\tabw \setbox0=\hbox{\tt\space} \tabw=8\wd0 % tab amount % \def\starttabbox{\setbox0=\hbox\bgroup} % Allow an option to not replace quotes with a regular directed right % quote/apostrophe (char 0x27), but instead use the undirected quote % from cmtt (char 0x0d). The undirected quote is ugly, so don't make it % the default, but it works for pasting with more pdf viewers (at least % evince), the lilypond developers report. xpdf does work with the % regular 0x27. % \def\codequoteright{% \expandafter\ifx\csname SETcodequoteundirected\endcsname\relax '% \else \char'15 \fi } % % and a similar option for the left quote char vs. a grave accent. % Modern fonts display ASCII 0x60 as a grave accent, so some people like % the code environments to do likewise. % \def\codequoteleft{% \expandafter\ifx\csname SETcodequotebacktick\endcsname\relax `% \else \char'22 \fi } % \begingroup \catcode`\^^I=\active \gdef\tabexpand{% \catcode`\^^I=\active \def^^I{\leavevmode\egroup \dimen0=\wd0 % the width so far, or since the previous tab \divide\dimen0 by\tabw \multiply\dimen0 by\tabw % compute previous multiple of \tabw \advance\dimen0 by\tabw % advance to next multiple of \tabw \wd0=\dimen0 \box0 \starttabbox }% } \catcode`\'=\active \gdef\rquoteexpand{\catcode\rquoteChar=\active \def'{\codequoteright}}% % \catcode`\`=\active \gdef\lquoteexpand{\catcode\lquoteChar=\active \def`{\codequoteleft}}% % \gdef\quoteexpand{\rquoteexpand \lquoteexpand}% \endgroup % start the verbatim environment. \def\setupverbatim{% \let\nonarrowing = t% \nonfillstart % Easiest (and conventionally used) font for verbatim \tt \def\par{\leavevmode\egroup\box0\endgraf}% \catcode`\`=\active \tabexpand \quoteexpand % Respect line breaks, % print special symbols as themselves, and % make each space count % must do in this order: \obeylines \uncatcodespecials \sepspaces \everypar{\starttabbox}% } % Do the @verb magic: verbatim text is quoted by unique % delimiter characters. Before first delimiter expect a % right brace, after last delimiter expect closing brace: % % \def\doverb'{'#1'}'{#1} % % [Knuth] p. 382; only eat outer {} \begingroup \catcode`[=1\catcode`]=2\catcode`\{=\other\catcode`\}=\other \gdef\doverb{#1[\def\next##1#1}[##1\endgroup]\next] \endgroup % \def\verb{\begingroup\setupverb\doverb} % % % Do the @verbatim magic: define the macro \doverbatim so that % the (first) argument ends when '@end verbatim' is reached, ie: % % \def\doverbatim#1@end verbatim{#1} % % For Texinfo it's a lot easier than for LaTeX, % because texinfo's \verbatim doesn't stop at '\end{verbatim}': % we need not redefine '\', '{' and '}'. % % Inspired by LaTeX's verbatim command set [latex.ltx] % \begingroup \catcode`\ =\active \obeylines % % ignore everything up to the first ^^M, that's the newline at the end % of the @verbatim input line itself. Otherwise we get an extra blank % line in the output. \xdef\doverbatim#1^^M#2@end verbatim{#2\noexpand\end\gobble verbatim}% % We really want {...\end verbatim} in the body of the macro, but % without the active space; thus we have to use \xdef and \gobble. \endgroup % \envdef\verbatim{% \setupverbatim\doverbatim } \let\Everbatim = \afterenvbreak % @verbatiminclude FILE - insert text of file in verbatim environment. % \def\verbatiminclude{\parseargusing\filenamecatcodes\doverbatiminclude} % \def\doverbatiminclude#1{% {% \makevalueexpandable \setupverbatim \input #1 \afterenvbreak }% } % @copying ... @end copying. % Save the text away for @insertcopying later. % % We save the uninterpreted tokens, rather than creating a box. % Saving the text in a box would be much easier, but then all the % typesetting commands (@smallbook, font changes, etc.) have to be done % beforehand -- and a) we want @copying to be done first in the source % file; b) letting users define the frontmatter in as flexible order as % possible is very desirable. % \def\copying{\checkenv{}\begingroup\scanargctxt\docopying} \def\docopying#1@end copying{\endgroup\def\copyingtext{#1}} % \def\insertcopying{% \begingroup \parindent = 0pt % paragraph indentation looks wrong on title page \scanexp\copyingtext \endgroup } \message{defuns,} % @defun etc. \newskip\defbodyindent \defbodyindent=.4in \newskip\defargsindent \defargsindent=50pt \newskip\deflastargmargin \deflastargmargin=18pt \newcount\defunpenalty % Start the processing of @deffn: \def\startdefun{% \ifnum\lastpenalty<10000 \medbreak \defunpenalty=10003 % Will keep this @deffn together with the % following @def command, see below. \else % If there are two @def commands in a row, we'll have a \nobreak, % which is there to keep the function description together with its % header. But if there's nothing but headers, we need to allow a % break somewhere. Check specifically for penalty 10002, inserted % by \printdefunline, instead of 10000, since the sectioning % commands also insert a nobreak penalty, and we don't want to allow % a break between a section heading and a defun. % % As a minor refinement, we avoid "club" headers by signalling % with penalty of 10003 after the very first @deffn in the % sequence (see above), and penalty of 10002 after any following % @def command. \ifnum\lastpenalty=10002 \penalty2000 \else \defunpenalty=10002 \fi % % Similarly, after a section heading, do not allow a break. % But do insert the glue. \medskip % preceded by discardable penalty, so not a breakpoint \fi % \parindent=0in \advance\leftskip by \defbodyindent \exdentamount=\defbodyindent } \def\dodefunx#1{% % First, check whether we are in the right environment: \checkenv#1% % % As above, allow line break if we have multiple x headers in a row. % It's not a great place, though. \ifnum\lastpenalty=10002 \penalty3000 \else \defunpenalty=10002 \fi % % And now, it's time to reuse the body of the original defun: \expandafter\gobbledefun#1% } \def\gobbledefun#1\startdefun{} % \printdefunline \deffnheader{text} % \def\printdefunline#1#2{% \begingroup % call \deffnheader: #1#2 \endheader % common ending: \interlinepenalty = 10000 \advance\rightskip by 0pt plus 1fil \endgraf \nobreak\vskip -\parskip \penalty\defunpenalty % signal to \startdefun and \dodefunx % Some of the @defun-type tags do not enable magic parentheses, % rendering the following check redundant. But we don't optimize. \checkparencounts \endgroup } \def\Edefun{\endgraf\medbreak} % \makedefun{deffn} creates \deffn, \deffnx and \Edeffn; % the only thing remainnig is to define \deffnheader. % \def\makedefun#1{% \expandafter\let\csname E#1\endcsname = \Edefun \edef\temp{\noexpand\domakedefun \makecsname{#1}\makecsname{#1x}\makecsname{#1header}}% \temp } % \domakedefun \deffn \deffnx \deffnheader % % Define \deffn and \deffnx, without parameters. % \deffnheader has to be defined explicitly. % \def\domakedefun#1#2#3{% \envdef#1{% \startdefun \parseargusing\activeparens{\printdefunline#3}% }% \def#2{\dodefunx#1}% \def#3% } %%% Untyped functions: % @deffn category name args \makedefun{deffn}{\deffngeneral{}} % @deffn category class name args \makedefun{defop}#1 {\defopon{#1\ \putwordon}} % \defopon {category on}class name args \def\defopon#1#2 {\deffngeneral{\putwordon\ \code{#2}}{#1\ \code{#2}} } % \deffngeneral {subind}category name args % \def\deffngeneral#1#2 #3 #4\endheader{% % Remember that \dosubind{fn}{foo}{} is equivalent to \doind{fn}{foo}. \dosubind{fn}{\code{#3}}{#1}% \defname{#2}{}{#3}\magicamp\defunargs{#4\unskip}% } %%% Typed functions: % @deftypefn category type name args \makedefun{deftypefn}{\deftypefngeneral{}} % @deftypeop category class type name args \makedefun{deftypeop}#1 {\deftypeopon{#1\ \putwordon}} % \deftypeopon {category on}class type name args \def\deftypeopon#1#2 {\deftypefngeneral{\putwordon\ \code{#2}}{#1\ \code{#2}} } % \deftypefngeneral {subind}category type name args % \def\deftypefngeneral#1#2 #3 #4 #5\endheader{% \dosubind{fn}{\code{#4}}{#1}% \defname{#2}{#3}{#4}\defunargs{#5\unskip}% } %%% Typed variables: % @deftypevr category type var args \makedefun{deftypevr}{\deftypecvgeneral{}} % @deftypecv category class type var args \makedefun{deftypecv}#1 {\deftypecvof{#1\ \putwordof}} % \deftypecvof {category of}class type var args \def\deftypecvof#1#2 {\deftypecvgeneral{\putwordof\ \code{#2}}{#1\ \code{#2}} } % \deftypecvgeneral {subind}category type var args % \def\deftypecvgeneral#1#2 #3 #4 #5\endheader{% \dosubind{vr}{\code{#4}}{#1}% \defname{#2}{#3}{#4}\defunargs{#5\unskip}% } %%% Untyped variables: % @defvr category var args \makedefun{defvr}#1 {\deftypevrheader{#1} {} } % @defcv category class var args \makedefun{defcv}#1 {\defcvof{#1\ \putwordof}} % \defcvof {category of}class var args \def\defcvof#1#2 {\deftypecvof{#1}#2 {} } %%% Type: % @deftp category name args \makedefun{deftp}#1 #2 #3\endheader{% \doind{tp}{\code{#2}}% \defname{#1}{}{#2}\defunargs{#3\unskip}% } % Remaining @defun-like shortcuts: \makedefun{defun}{\deffnheader{\putwordDeffunc} } \makedefun{defmac}{\deffnheader{\putwordDefmac} } \makedefun{defspec}{\deffnheader{\putwordDefspec} } \makedefun{deftypefun}{\deftypefnheader{\putwordDeffunc} } \makedefun{defvar}{\defvrheader{\putwordDefvar} } \makedefun{defopt}{\defvrheader{\putwordDefopt} } \makedefun{deftypevar}{\deftypevrheader{\putwordDefvar} } \makedefun{defmethod}{\defopon\putwordMethodon} \makedefun{deftypemethod}{\deftypeopon\putwordMethodon} \makedefun{defivar}{\defcvof\putwordInstanceVariableof} \makedefun{deftypeivar}{\deftypecvof\putwordInstanceVariableof} % \defname, which formats the name of the @def (not the args). % #1 is the category, such as "Function". % #2 is the return type, if any. % #3 is the function name. % % We are followed by (but not passed) the arguments, if any. % \def\defname#1#2#3{% % Get the values of \leftskip and \rightskip as they were outside the @def... \advance\leftskip by -\defbodyindent % % How we'll format the type name. Putting it in brackets helps % distinguish it from the body text that may end up on the next line % just below it. \def\temp{#1}% \setbox0=\hbox{\kern\deflastargmargin \ifx\temp\empty\else [\rm\temp]\fi} % % Figure out line sizes for the paragraph shape. % The first line needs space for \box0; but if \rightskip is nonzero, % we need only space for the part of \box0 which exceeds it: \dimen0=\hsize \advance\dimen0 by -\wd0 \advance\dimen0 by \rightskip % The continuations: \dimen2=\hsize \advance\dimen2 by -\defargsindent % (plain.tex says that \dimen1 should be used only as global.) \parshape 2 0in \dimen0 \defargsindent \dimen2 % % Put the type name to the right margin. \noindent \hbox to 0pt{% \hfil\box0 \kern-\hsize % \hsize has to be shortened this way: \kern\leftskip % Intentionally do not respect \rightskip, since we need the space. }% % % Allow all lines to be underfull without complaint: \tolerance=10000 \hbadness=10000 \exdentamount=\defbodyindent {% % defun fonts. We use typewriter by default (used to be bold) because: % . we're printing identifiers, they should be in tt in principle. % . in languages with many accents, such as Czech or French, it's % common to leave accents off identifiers. The result looks ok in % tt, but exceedingly strange in rm. % . we don't want -- and --- to be treated as ligatures. % . this still does not fix the ?` and !` ligatures, but so far no % one has made identifiers using them :). \df \tt \def\temp{#2}% return value type \ifx\temp\empty\else \tclose{\temp} \fi #3% output function name }% {\rm\enskip}% hskip 0.5 em of \tenrm % \boldbrax % arguments will be output next, if any. } % Print arguments in slanted roman (not ttsl), inconsistently with using % tt for the name. This is because literal text is sometimes needed in % the argument list (groff manual), and ttsl and tt are not very % distinguishable. Prevent hyphenation at `-' chars. % \def\defunargs#1{% % use sl by default (not ttsl), % tt for the names. \df \sl \hyphenchar\font=0 % % On the other hand, if an argument has two dashes (for instance), we % want a way to get ttsl. Let's try @var for that. \let\var=\ttslanted #1% \sl\hyphenchar\font=45 } % We want ()&[] to print specially on the defun line. % \def\activeparens{% \catcode`\(=\active \catcode`\)=\active \catcode`\[=\active \catcode`\]=\active \catcode`\&=\active } % Make control sequences which act like normal parenthesis chars. \let\lparen = ( \let\rparen = ) % Be sure that we always have a definition for `(', etc. For example, % if the fn name has parens in it, \boldbrax will not be in effect yet, % so TeX would otherwise complain about undefined control sequence. { \activeparens \global\let(=\lparen \global\let)=\rparen \global\let[=\lbrack \global\let]=\rbrack \global\let& = \& \gdef\boldbrax{\let(=\opnr\let)=\clnr\let[=\lbrb\let]=\rbrb} \gdef\magicamp{\let&=\amprm} } \newcount\parencount % If we encounter &foo, then turn on ()-hacking afterwards \newif\ifampseen \def\amprm#1 {\ampseentrue{\bf\ }} \def\parenfont{% \ifampseen % At the first level, print parens in roman, % otherwise use the default font. \ifnum \parencount=1 \rm \fi \else % The \sf parens (in \boldbrax) actually are a little bolder than % the contained text. This is especially needed for [ and ] . \sf \fi } \def\infirstlevel#1{% \ifampseen \ifnum\parencount=1 #1% \fi \fi } \def\bfafterword#1 {#1 \bf} \def\opnr{% \global\advance\parencount by 1 {\parenfont(}% \infirstlevel \bfafterword } \def\clnr{% {\parenfont)}% \infirstlevel \sl \global\advance\parencount by -1 } \newcount\brackcount \def\lbrb{% \global\advance\brackcount by 1 {\bf[}% } \def\rbrb{% {\bf]}% \global\advance\brackcount by -1 } \def\checkparencounts{% \ifnum\parencount=0 \else \badparencount \fi \ifnum\brackcount=0 \else \badbrackcount \fi } \def\badparencount{% \errmessage{Unbalanced parentheses in @def}% \global\parencount=0 } \def\badbrackcount{% \errmessage{Unbalanced square braces in @def}% \global\brackcount=0 } \message{macros,} % @macro. % To do this right we need a feature of e-TeX, \scantokens, % which we arrange to emulate with a temporary file in ordinary TeX. \ifx\eTeXversion\undefined \newwrite\macscribble \def\scantokens#1{% \toks0={#1}% \immediate\openout\macscribble=\jobname.tmp \immediate\write\macscribble{\the\toks0}% \immediate\closeout\macscribble \input \jobname.tmp } \fi \def\scanmacro#1{% \begingroup \newlinechar`\^^M \let\xeatspaces\eatspaces % Undo catcode changes of \startcontents and \doprintindex % When called from @insertcopying or (short)caption, we need active % backslash to get it printed correctly. Previously, we had % \catcode`\\=\other instead. We'll see whether a problem appears % with macro expansion. --kasal, 19aug04 \catcode`\@=0 \catcode`\\=\active \escapechar=`\@ % ... and \example \spaceisspace % % Append \endinput to make sure that TeX does not see the ending newline. % I've verified that it is necessary both for e-TeX and for ordinary TeX % --kasal, 29nov03 \scantokens{#1\endinput}% \endgroup } \def\scanexp#1{% \edef\temp{\noexpand\scanmacro{#1}}% \temp } \newcount\paramno % Count of parameters \newtoks\macname % Macro name \newif\ifrecursive % Is it recursive? % List of all defined macros in the form % \definedummyword\macro1\definedummyword\macro2... % Currently is also contains all @aliases; the list can be split % if there is a need. \def\macrolist{} % Add the macro to \macrolist \def\addtomacrolist#1{\expandafter \addtomacrolistxxx \csname#1\endcsname} \def\addtomacrolistxxx#1{% \toks0 = \expandafter{\macrolist\definedummyword#1}% \xdef\macrolist{\the\toks0}% } % Utility routines. % This does \let #1 = #2, with \csnames; that is, % \let \csname#1\endcsname = \csname#2\endcsname % (except of course we have to play expansion games). % \def\cslet#1#2{% \expandafter\let \csname#1\expandafter\endcsname \csname#2\endcsname } % Trim leading and trailing spaces off a string. % Concepts from aro-bend problem 15 (see CTAN). {\catcode`\@=11 \gdef\eatspaces #1{\expandafter\trim@\expandafter{#1 }} \gdef\trim@ #1{\trim@@ @#1 @ #1 @ @@} \gdef\trim@@ #1@ #2@ #3@@{\trim@@@\empty #2 @} \def\unbrace#1{#1} \unbrace{\gdef\trim@@@ #1 } #2@{#1} } % Trim a single trailing ^^M off a string. {\catcode`\^^M=\other \catcode`\Q=3% \gdef\eatcr #1{\eatcra #1Q^^MQ}% \gdef\eatcra#1^^MQ{\eatcrb#1Q}% \gdef\eatcrb#1Q#2Q{#1}% } % Macro bodies are absorbed as an argument in a context where % all characters are catcode 10, 11 or 12, except \ which is active % (as in normal texinfo). It is necessary to change the definition of \. % It's necessary to have hard CRs when the macro is executed. This is % done by making ^^M (\endlinechar) catcode 12 when reading the macro % body, and then making it the \newlinechar in \scanmacro. \def\scanctxt{% \catcode`\"=\other \catcode`\+=\other \catcode`\<=\other \catcode`\>=\other \catcode`\@=\other \catcode`\^=\other \catcode`\_=\other \catcode`\|=\other \catcode`\~=\other } \def\scanargctxt{% \scanctxt \catcode`\\=\other \catcode`\^^M=\other } \def\macrobodyctxt{% \scanctxt \catcode`\{=\other \catcode`\}=\other \catcode`\^^M=\other \usembodybackslash } \def\macroargctxt{% \scanctxt \catcode`\\=\other } % \mbodybackslash is the definition of \ in @macro bodies. % It maps \foo\ => \csname macarg.foo\endcsname => #N % where N is the macro parameter number. % We define \csname macarg.\endcsname to be \realbackslash, so % \\ in macro replacement text gets you a backslash. {\catcode`@=0 @catcode`@\=@active @gdef@usembodybackslash{@let\=@mbodybackslash} @gdef@mbodybackslash#1\{@csname macarg.#1@endcsname} } \expandafter\def\csname macarg.\endcsname{\realbackslash} \def\macro{\recursivefalse\parsearg\macroxxx} \def\rmacro{\recursivetrue\parsearg\macroxxx} \def\macroxxx#1{% \getargs{#1}% now \macname is the macname and \argl the arglist \ifx\argl\empty % no arguments \paramno=0% \else \expandafter\parsemargdef \argl;% \fi \if1\csname ismacro.\the\macname\endcsname \message{Warning: redefining \the\macname}% \else \expandafter\ifx\csname \the\macname\endcsname \relax \else \errmessage{Macro name \the\macname\space already defined}\fi \global\cslet{macsave.\the\macname}{\the\macname}% \global\expandafter\let\csname ismacro.\the\macname\endcsname=1% \addtomacrolist{\the\macname}% \fi \begingroup \macrobodyctxt \ifrecursive \expandafter\parsermacbody \else \expandafter\parsemacbody \fi} \parseargdef\unmacro{% \if1\csname ismacro.#1\endcsname \global\cslet{#1}{macsave.#1}% \global\expandafter\let \csname ismacro.#1\endcsname=0% % Remove the macro name from \macrolist: \begingroup \expandafter\let\csname#1\endcsname \relax \let\definedummyword\unmacrodo \xdef\macrolist{\macrolist}% \endgroup \else \errmessage{Macro #1 not defined}% \fi } % Called by \do from \dounmacro on each macro. The idea is to omit any % macro definitions that have been changed to \relax. % \def\unmacrodo#1{% \ifx #1\relax % remove this \else \noexpand\definedummyword \noexpand#1% \fi } % This makes use of the obscure feature that if the last token of a % is #, then the preceding argument is delimited by % an opening brace, and that opening brace is not consumed. \def\getargs#1{\getargsxxx#1{}} \def\getargsxxx#1#{\getmacname #1 \relax\getmacargs} \def\getmacname #1 #2\relax{\macname={#1}} \def\getmacargs#1{\def\argl{#1}} % Parse the optional {params} list. Set up \paramno and \paramlist % so \defmacro knows what to do. Define \macarg.blah for each blah % in the params list, to be ##N where N is the position in that list. % That gets used by \mbodybackslash (above). % We need to get `macro parameter char #' into several definitions. % The technique used is stolen from LaTeX: let \hash be something % unexpandable, insert that wherever you need a #, and then redefine % it to # just before using the token list produced. % % The same technique is used to protect \eatspaces till just before % the macro is used. \def\parsemargdef#1;{\paramno=0\def\paramlist{}% \let\hash\relax\let\xeatspaces\relax\parsemargdefxxx#1,;,} \def\parsemargdefxxx#1,{% \if#1;\let\next=\relax \else \let\next=\parsemargdefxxx \advance\paramno by 1% \expandafter\edef\csname macarg.\eatspaces{#1}\endcsname {\xeatspaces{\hash\the\paramno}}% \edef\paramlist{\paramlist\hash\the\paramno,}% \fi\next} % These two commands read recursive and nonrecursive macro bodies. % (They're different since rec and nonrec macros end differently.) \long\def\parsemacbody#1@end macro% {\xdef\temp{\eatcr{#1}}\endgroup\defmacro}% \long\def\parsermacbody#1@end rmacro% {\xdef\temp{\eatcr{#1}}\endgroup\defmacro}% % This defines the macro itself. There are six cases: recursive and % nonrecursive macros of zero, one, and many arguments. % Much magic with \expandafter here. % \xdef is used so that macro definitions will survive the file % they're defined in; @include reads the file inside a group. \def\defmacro{% \let\hash=##% convert placeholders to macro parameter chars \ifrecursive \ifcase\paramno % 0 \expandafter\xdef\csname\the\macname\endcsname{% \noexpand\scanmacro{\temp}}% \or % 1 \expandafter\xdef\csname\the\macname\endcsname{% \bgroup\noexpand\macroargctxt \noexpand\braceorline \expandafter\noexpand\csname\the\macname xxx\endcsname}% \expandafter\xdef\csname\the\macname xxx\endcsname##1{% \egroup\noexpand\scanmacro{\temp}}% \else % many \expandafter\xdef\csname\the\macname\endcsname{% \bgroup\noexpand\macroargctxt \noexpand\csname\the\macname xx\endcsname}% \expandafter\xdef\csname\the\macname xx\endcsname##1{% \expandafter\noexpand\csname\the\macname xxx\endcsname ##1,}% \expandafter\expandafter \expandafter\xdef \expandafter\expandafter \csname\the\macname xxx\endcsname \paramlist{\egroup\noexpand\scanmacro{\temp}}% \fi \else \ifcase\paramno % 0 \expandafter\xdef\csname\the\macname\endcsname{% \noexpand\norecurse{\the\macname}% \noexpand\scanmacro{\temp}\egroup}% \or % 1 \expandafter\xdef\csname\the\macname\endcsname{% \bgroup\noexpand\macroargctxt \noexpand\braceorline \expandafter\noexpand\csname\the\macname xxx\endcsname}% \expandafter\xdef\csname\the\macname xxx\endcsname##1{% \egroup \noexpand\norecurse{\the\macname}% \noexpand\scanmacro{\temp}\egroup}% \else % many \expandafter\xdef\csname\the\macname\endcsname{% \bgroup\noexpand\macroargctxt \expandafter\noexpand\csname\the\macname xx\endcsname}% \expandafter\xdef\csname\the\macname xx\endcsname##1{% \expandafter\noexpand\csname\the\macname xxx\endcsname ##1,}% \expandafter\expandafter \expandafter\xdef \expandafter\expandafter \csname\the\macname xxx\endcsname \paramlist{% \egroup \noexpand\norecurse{\the\macname}% \noexpand\scanmacro{\temp}\egroup}% \fi \fi} \def\norecurse#1{\bgroup\cslet{#1}{macsave.#1}} % \braceorline decides whether the next nonwhitespace character is a % {. If so it reads up to the closing }, if not, it reads the whole % line. Whatever was read is then fed to the next control sequence % as an argument (by \parsebrace or \parsearg) \def\braceorline#1{\let\macnamexxx=#1\futurelet\nchar\braceorlinexxx} \def\braceorlinexxx{% \ifx\nchar\bgroup\else \expandafter\parsearg \fi \macnamexxx} % @alias. % We need some trickery to remove the optional spaces around the equal % sign. Just make them active and then expand them all to nothing. \def\alias{\parseargusing\obeyspaces\aliasxxx} \def\aliasxxx #1{\aliasyyy#1\relax} \def\aliasyyy #1=#2\relax{% {% \expandafter\let\obeyedspace=\empty \addtomacrolist{#1}% \xdef\next{\global\let\makecsname{#1}=\makecsname{#2}}% }% \next } \message{cross references,} \newwrite\auxfile \newif\ifhavexrefs % True if xref values are known. \newif\ifwarnedxrefs % True if we warned once that they aren't known. % @inforef is relatively simple. \def\inforef #1{\inforefzzz #1,,,,**} \def\inforefzzz #1,#2,#3,#4**{\putwordSee{} \putwordInfo{} \putwordfile{} \file{\ignorespaces #3{}}, node \samp{\ignorespaces#1{}}} % @node's only job in TeX is to define \lastnode, which is used in % cross-references. The @node line might or might not have commas, and % might or might not have spaces before the first comma, like: % @node foo , bar , ... % We don't want such trailing spaces in the node name. % \parseargdef\node{\checkenv{}\donode #1 ,\finishnodeparse} % % also remove a trailing comma, in case of something like this: % @node Help-Cross, , , Cross-refs \def\donode#1 ,#2\finishnodeparse{\dodonode #1,\finishnodeparse} \def\dodonode#1,#2\finishnodeparse{\gdef\lastnode{#1}} \let\nwnode=\node \let\lastnode=\empty % Write a cross-reference definition for the current node. #1 is the % type (Ynumbered, Yappendix, Ynothing). % \def\donoderef#1{% \ifx\lastnode\empty\else \setref{\lastnode}{#1}% \global\let\lastnode=\empty \fi } % @anchor{NAME} -- define xref target at arbitrary point. % \newcount\savesfregister % \def\savesf{\relax \ifhmode \savesfregister=\spacefactor \fi} \def\restoresf{\relax \ifhmode \spacefactor=\savesfregister \fi} \def\anchor#1{\savesf \setref{#1}{Ynothing}\restoresf \ignorespaces} % \setref{NAME}{SNT} defines a cross-reference point NAME (a node or an % anchor), which consists of three parts: % 1) NAME-title - the current sectioning name taken from \thissection, % or the anchor name. % 2) NAME-snt - section number and type, passed as the SNT arg, or % empty for anchors. % 3) NAME-pg - the page number. % % This is called from \donoderef, \anchor, and \dofloat. In the case of % floats, there is an additional part, which is not written here: % 4) NAME-lof - the text as it should appear in a @listoffloats. % \def\setref#1#2{% \pdfmkdest{#1}% \iflinks {% \atdummies % preserve commands, but don't expand them \edef\writexrdef##1##2{% \write\auxfile{@xrdef{#1-% #1 of \setref, expanded by the \edef ##1}{##2}}% these are parameters of \writexrdef }% \toks0 = \expandafter{\thissection}% \immediate \writexrdef{title}{\the\toks0 }% \immediate \writexrdef{snt}{\csname #2\endcsname}% \Ynumbered etc. \safewhatsit{\writexrdef{pg}{\folio}}% will be written later, during \shipout }% \fi } % @xref, @pxref, and @ref generate cross-references. For \xrefX, #1 is % the node name, #2 the name of the Info cross-reference, #3 the printed % node name, #4 the name of the Info file, #5 the name of the printed % manual. All but the node name can be omitted. % \def\pxref#1{\putwordsee{} \xrefX[#1,,,,,,,]} \def\xref#1{\putwordSee{} \xrefX[#1,,,,,,,]} \def\ref#1{\xrefX[#1,,,,,,,]} \def\xrefX[#1,#2,#3,#4,#5,#6]{\begingroup \unsepspaces \def\printedmanual{\ignorespaces #5}% \def\printedrefname{\ignorespaces #3}% \setbox1=\hbox{\printedmanual\unskip}% \setbox0=\hbox{\printedrefname\unskip}% \ifdim \wd0 = 0pt % No printed node name was explicitly given. \expandafter\ifx\csname SETxref-automatic-section-title\endcsname\relax % Use the node name inside the square brackets. \def\printedrefname{\ignorespaces #1}% \else % Use the actual chapter/section title appear inside % the square brackets. Use the real section title if we have it. \ifdim \wd1 > 0pt % It is in another manual, so we don't have it. \def\printedrefname{\ignorespaces #1}% \else \ifhavexrefs % We know the real title if we have the xref values. \def\printedrefname{\refx{#1-title}{}}% \else % Otherwise just copy the Info node name. \def\printedrefname{\ignorespaces #1}% \fi% \fi \fi \fi % % Make link in pdf output. \ifpdf \leavevmode \getfilename{#4}% {\indexnofonts \turnoffactive % See comments at \activebackslashdouble. {\activebackslashdouble \xdef\pdfxrefdest{#1}% \backslashparens\pdfxrefdest}% % \ifnum\filenamelength>0 \startlink attr{/Border [0 0 0]}% goto file{\the\filename.pdf} name{\pdfxrefdest}% \else \startlink attr{/Border [0 0 0]}% goto name{\pdfmkpgn{\pdfxrefdest}}% \fi }% \linkcolor \fi % % Float references are printed completely differently: "Figure 1.2" % instead of "[somenode], p.3". We distinguish them by the % LABEL-title being set to a magic string. {% % Have to otherify everything special to allow the \csname to % include an _ in the xref name, etc. \indexnofonts \turnoffactive \expandafter\global\expandafter\let\expandafter\Xthisreftitle \csname XR#1-title\endcsname }% \iffloat\Xthisreftitle % If the user specified the print name (third arg) to the ref, % print it instead of our usual "Figure 1.2". \ifdim\wd0 = 0pt \refx{#1-snt}{}% \else \printedrefname \fi % % if the user also gave the printed manual name (fifth arg), append % "in MANUALNAME". \ifdim \wd1 > 0pt \space \putwordin{} \cite{\printedmanual}% \fi \else % node/anchor (non-float) references. % % If we use \unhbox0 and \unhbox1 to print the node names, TeX does not % insert empty discretionaries after hyphens, which means that it will % not find a line break at a hyphen in a node names. Since some manuals % are best written with fairly long node names, containing hyphens, this % is a loss. Therefore, we give the text of the node name again, so it % is as if TeX is seeing it for the first time. \ifdim \wd1 > 0pt \putwordsection{} ``\printedrefname'' \putwordin{} \cite{\printedmanual}% \else % _ (for example) has to be the character _ for the purposes of the % control sequence corresponding to the node, but it has to expand % into the usual \leavevmode...\vrule stuff for purposes of % printing. So we \turnoffactive for the \refx-snt, back on for the % printing, back off for the \refx-pg. {\turnoffactive % Only output a following space if the -snt ref is nonempty; for % @unnumbered and @anchor, it won't be. \setbox2 = \hbox{\ignorespaces \refx{#1-snt}{}}% \ifdim \wd2 > 0pt \refx{#1-snt}\space\fi }% % output the `[mynode]' via a macro so it can be overridden. \xrefprintnodename\printedrefname % % But we always want a comma and a space: ,\space % % output the `page 3'. \turnoffactive \putwordpage\tie\refx{#1-pg}{}% \fi \fi \endlink \endgroup} % This macro is called from \xrefX for the `[nodename]' part of xref % output. It's a separate macro only so it can be changed more easily, % since square brackets don't work well in some documents. Particularly % one that Bob is working on :). % \def\xrefprintnodename#1{[#1]} % Things referred to by \setref. % \def\Ynothing{} \def\Yomitfromtoc{} \def\Ynumbered{% \ifnum\secno=0 \putwordChapter@tie \the\chapno \else \ifnum\subsecno=0 \putwordSection@tie \the\chapno.\the\secno \else \ifnum\subsubsecno=0 \putwordSection@tie \the\chapno.\the\secno.\the\subsecno \else \putwordSection@tie \the\chapno.\the\secno.\the\subsecno.\the\subsubsecno \fi\fi\fi } \def\Yappendix{% \ifnum\secno=0 \putwordAppendix@tie @char\the\appendixno{}% \else \ifnum\subsecno=0 \putwordSection@tie @char\the\appendixno.\the\secno \else \ifnum\subsubsecno=0 \putwordSection@tie @char\the\appendixno.\the\secno.\the\subsecno \else \putwordSection@tie @char\the\appendixno.\the\secno.\the\subsecno.\the\subsubsecno \fi\fi\fi } % Define \refx{NAME}{SUFFIX} to reference a cross-reference string named NAME. % If its value is nonempty, SUFFIX is output afterward. % \def\refx#1#2{% {% \indexnofonts \otherbackslash \expandafter\global\expandafter\let\expandafter\thisrefX \csname XR#1\endcsname }% \ifx\thisrefX\relax % If not defined, say something at least. \angleleft un\-de\-fined\angleright \iflinks \ifhavexrefs \message{\linenumber Undefined cross reference `#1'.}% \else \ifwarnedxrefs\else \global\warnedxrefstrue \message{Cross reference values unknown; you must run TeX again.}% \fi \fi \fi \else % It's defined, so just use it. \thisrefX \fi #2% Output the suffix in any case. } % This is the macro invoked by entries in the aux file. Usually it's % just a \def (we prepend XR to the control sequence name to avoid % collisions). But if this is a float type, we have more work to do. % \def\xrdef#1#2{% {% The node name might contain 8-bit characters, which in our current % implementation are changed to commands like @'e. Don't let these % mess up the control sequence name. \indexnofonts \turnoffactive \xdef\safexrefname{#1}% }% % \expandafter\gdef\csname XR\safexrefname\endcsname{#2}% remember this xref % % Was that xref control sequence that we just defined for a float? \expandafter\iffloat\csname XR\safexrefname\endcsname % it was a float, and we have the (safe) float type in \iffloattype. \expandafter\let\expandafter\floatlist \csname floatlist\iffloattype\endcsname % % Is this the first time we've seen this float type? \expandafter\ifx\floatlist\relax \toks0 = {\do}% yes, so just \do \else % had it before, so preserve previous elements in list. \toks0 = \expandafter{\floatlist\do}% \fi % % Remember this xref in the control sequence \floatlistFLOATTYPE, % for later use in \listoffloats. \expandafter\xdef\csname floatlist\iffloattype\endcsname{\the\toks0 {\safexrefname}}% \fi } % Read the last existing aux file, if any. No error if none exists. % \def\tryauxfile{% \openin 1 \jobname.aux \ifeof 1 \else \readdatafile{aux}% \global\havexrefstrue \fi \closein 1 } \def\setupdatafile{% \catcode`\^^@=\other \catcode`\^^A=\other \catcode`\^^B=\other \catcode`\^^C=\other \catcode`\^^D=\other \catcode`\^^E=\other \catcode`\^^F=\other \catcode`\^^G=\other \catcode`\^^H=\other \catcode`\^^K=\other \catcode`\^^L=\other \catcode`\^^N=\other \catcode`\^^P=\other \catcode`\^^Q=\other \catcode`\^^R=\other \catcode`\^^S=\other \catcode`\^^T=\other \catcode`\^^U=\other \catcode`\^^V=\other \catcode`\^^W=\other \catcode`\^^X=\other \catcode`\^^Z=\other \catcode`\^^[=\other \catcode`\^^\=\other \catcode`\^^]=\other \catcode`\^^^=\other \catcode`\^^_=\other % It was suggested to set the catcode of ^ to 7, which would allow ^^e4 etc. % in xref tags, i.e., node names. But since ^^e4 notation isn't % supported in the main text, it doesn't seem desirable. Furthermore, % that is not enough: for node names that actually contain a ^ % character, we would end up writing a line like this: 'xrdef {'hat % b-title}{'hat b} and \xrdef does a \csname...\endcsname on the first % argument, and \hat is not an expandable control sequence. It could % all be worked out, but why? Either we support ^^ or we don't. % % The other change necessary for this was to define \auxhat: % \def\auxhat{\def^{'hat }}% extra space so ok if followed by letter % and then to call \auxhat in \setq. % \catcode`\^=\other % % Special characters. Should be turned off anyway, but... \catcode`\~=\other \catcode`\[=\other \catcode`\]=\other \catcode`\"=\other \catcode`\_=\other \catcode`\|=\other \catcode`\<=\other \catcode`\>=\other \catcode`\$=\other \catcode`\#=\other \catcode`\&=\other \catcode`\%=\other \catcode`+=\other % avoid \+ for paranoia even though we've turned it off % % This is to support \ in node names and titles, since the \ % characters end up in a \csname. It's easier than % leaving it active and making its active definition an actual \ % character. What I don't understand is why it works in the *value* % of the xrdef. Seems like it should be a catcode12 \, and that % should not typeset properly. But it works, so I'm moving on for % now. --karl, 15jan04. \catcode`\\=\other % % Make the characters 128-255 be printing characters. {% \count1=128 \def\loop{% \catcode\count1=\other \advance\count1 by 1 \ifnum \count1<256 \loop \fi }% }% % % @ is our escape character in .aux files, and we need braces. \catcode`\{=1 \catcode`\}=2 \catcode`\@=0 } \def\readdatafile#1{% \begingroup \setupdatafile \input\jobname.#1 \endgroup} \message{insertions,} % including footnotes. \newcount \footnoteno % The trailing space in the following definition for supereject is % vital for proper filling; pages come out unaligned when you do a % pagealignmacro call if that space before the closing brace is % removed. (Generally, numeric constants should always be followed by a % space to prevent strange expansion errors.) \def\supereject{\par\penalty -20000\footnoteno =0 } % @footnotestyle is meaningful for info output only. \let\footnotestyle=\comment {\catcode `\@=11 % % Auto-number footnotes. Otherwise like plain. \gdef\footnote{% \let\indent=\ptexindent \let\noindent=\ptexnoindent \global\advance\footnoteno by \@ne \edef\thisfootno{$^{\the\footnoteno}$}% % % In case the footnote comes at the end of a sentence, preserve the % extra spacing after we do the footnote number. \let\@sf\empty \ifhmode\edef\@sf{\spacefactor\the\spacefactor}\ptexslash\fi % % Remove inadvertent blank space before typesetting the footnote number. \unskip \thisfootno\@sf \dofootnote }% % Don't bother with the trickery in plain.tex to not require the % footnote text as a parameter. Our footnotes don't need to be so general. % % Oh yes, they do; otherwise, @ifset (and anything else that uses % \parseargline) fails inside footnotes because the tokens are fixed when % the footnote is read. --karl, 16nov96. % \gdef\dofootnote{% \insert\footins\bgroup % We want to typeset this text as a normal paragraph, even if the % footnote reference occurs in (for example) a display environment. % So reset some parameters. \hsize=\pagewidth \interlinepenalty\interfootnotelinepenalty \splittopskip\ht\strutbox % top baseline for broken footnotes \splitmaxdepth\dp\strutbox \floatingpenalty\@MM \leftskip\z@skip \rightskip\z@skip \spaceskip\z@skip \xspaceskip\z@skip \parindent\defaultparindent % \smallfonts \rm % % Because we use hanging indentation in footnotes, a @noindent appears % to exdent this text, so make it be a no-op. makeinfo does not use % hanging indentation so @noindent can still be needed within footnote % text after an @example or the like (not that this is good style). \let\noindent = \relax % % Hang the footnote text off the number. Use \everypar in case the % footnote extends for more than one paragraph. \everypar = {\hang}% \textindent{\thisfootno}% % % Don't crash into the line above the footnote text. Since this % expands into a box, it must come within the paragraph, lest it % provide a place where TeX can split the footnote. \footstrut \futurelet\next\fo@t } }%end \catcode `\@=11 % In case a @footnote appears in a vbox, save the footnote text and create % the real \insert just after the vbox finished. Otherwise, the insertion % would be lost. -% Similarily, if a @footnote appears inside an alignment, save the footnote +% Similarly, if a @footnote appears inside an alignment, save the footnote % text to a box and make the \insert when a row of the table is finished. % And the same can be done for other insert classes. --kasal, 16nov03. % Replace the \insert primitive by a cheating macro. % Deeper inside, just make sure that the saved insertions are not spilled % out prematurely. % \def\startsavinginserts{% \ifx \insert\ptexinsert \let\insert\saveinsert \else \let\checkinserts\relax \fi } % This \insert replacement works for both \insert\footins{foo} and % \insert\footins\bgroup foo\egroup, but it doesn't work for \insert27{foo}. % \def\saveinsert#1{% \edef\next{\noexpand\savetobox \makeSAVEname#1}% \afterassignment\next % swallow the left brace \let\temp = } \def\makeSAVEname#1{\makecsname{SAVE\expandafter\gobble\string#1}} \def\savetobox#1{\global\setbox#1 = \vbox\bgroup \unvbox#1} \def\checksaveins#1{\ifvoid#1\else \placesaveins#1\fi} \def\placesaveins#1{% \ptexinsert \csname\expandafter\gobblesave\string#1\endcsname {\box#1}% } % eat @SAVE -- beware, all of them have catcode \other: { \def\dospecials{\do S\do A\do V\do E} \uncatcodespecials % ;-) \gdef\gobblesave @SAVE{} } % initialization: \def\newsaveins #1{% \edef\next{\noexpand\newsaveinsX \makeSAVEname#1}% \next } \def\newsaveinsX #1{% \csname newbox\endcsname #1% \expandafter\def\expandafter\checkinserts\expandafter{\checkinserts \checksaveins #1}% } % initialize: \let\checkinserts\empty \newsaveins\footins \newsaveins\margin % @image. We use the macros from epsf.tex to support this. % If epsf.tex is not installed and @image is used, we complain. % % Check for and read epsf.tex up front. If we read it only at @image % time, we might be inside a group, and then its definitions would get % undone and the next image would fail. \openin 1 = epsf.tex \ifeof 1 \else % Do not bother showing banner with epsf.tex v2.7k (available in % doc/epsf.tex and on ctan). \def\epsfannounce{\toks0 = }% \input epsf.tex \fi \closein 1 % % We will only complain once about lack of epsf.tex. \newif\ifwarnednoepsf \newhelp\noepsfhelp{epsf.tex must be installed for images to work. It is also included in the Texinfo distribution, or you can get it from ftp://tug.org/tex/epsf.tex.} % \def\image#1{% \ifx\epsfbox\undefined \ifwarnednoepsf \else \errhelp = \noepsfhelp \errmessage{epsf.tex not found, images will be ignored}% \global\warnednoepsftrue \fi \else \imagexxx #1,,,,,\finish \fi } % % Arguments to @image: % #1 is (mandatory) image filename; we tack on .eps extension. % #2 is (optional) width, #3 is (optional) height. % #4 is (ignored optional) html alt text. % #5 is (ignored optional) extension. % #6 is just the usual extra ignored arg for parsing this stuff. \newif\ifimagevmode \def\imagexxx#1,#2,#3,#4,#5,#6\finish{\begingroup \catcode`\^^M = 5 % in case we're inside an example \normalturnoffactive % allow _ et al. in names % If the image is by itself, center it. \ifvmode \imagevmodetrue \nobreak\bigskip % Usually we'll have text after the image which will insert % \parskip glue, so insert it here too to equalize the space % above and below. \nobreak\vskip\parskip \nobreak \line\bgroup \fi % % Output the image. \ifpdf \dopdfimage{#1}{#2}{#3}% \else % \epsfbox itself resets \epsf?size at each figure. \setbox0 = \hbox{\ignorespaces #2}\ifdim\wd0 > 0pt \epsfxsize=#2\relax \fi \setbox0 = \hbox{\ignorespaces #3}\ifdim\wd0 > 0pt \epsfysize=#3\relax \fi \epsfbox{#1.eps}% \fi % \ifimagevmode \egroup \bigbreak \fi % space after the image \endgroup} % @float FLOATTYPE,LABEL,LOC ... @end float for displayed figures, tables, % etc. We don't actually implement floating yet, we always include the % float "here". But it seemed the best name for the future. % \envparseargdef\float{\eatcommaspace\eatcommaspace\dofloat#1, , ,\finish} % There may be a space before second and/or third parameter; delete it. \def\eatcommaspace#1, {#1,} % #1 is the optional FLOATTYPE, the text label for this float, typically % "Figure", "Table", "Example", etc. Can't contain commas. If omitted, % this float will not be numbered and cannot be referred to. % % #2 is the optional xref label. Also must be present for the float to % be referable. % % #3 is the optional positioning argument; for now, it is ignored. It % will somehow specify the positions allowed to float to (here, top, bottom). % % We keep a separate counter for each FLOATTYPE, which we reset at each % chapter-level command. \let\resetallfloatnos=\empty % \def\dofloat#1,#2,#3,#4\finish{% \let\thiscaption=\empty \let\thisshortcaption=\empty % % don't lose footnotes inside @float. % % BEWARE: when the floats start float, we have to issue warning whenever an % insert appears inside a float which could possibly float. --kasal, 26may04 % \startsavinginserts % % We can't be used inside a paragraph. \par % \vtop\bgroup \def\floattype{#1}% \def\floatlabel{#2}% \def\floatloc{#3}% we do nothing with this yet. % \ifx\floattype\empty \let\safefloattype=\empty \else {% % the floattype might have accents or other special characters, % but we need to use it in a control sequence name. \indexnofonts \turnoffactive \xdef\safefloattype{\floattype}% }% \fi % % If label is given but no type, we handle that as the empty type. \ifx\floatlabel\empty \else % We want each FLOATTYPE to be numbered separately (Figure 1, % Table 1, Figure 2, ...). (And if no label, no number.) % \expandafter\getfloatno\csname\safefloattype floatno\endcsname \global\advance\floatno by 1 % {% % This magic value for \thissection is output by \setref as the % XREFLABEL-title value. \xrefX uses it to distinguish float % labels (which have a completely different output format) from % node and anchor labels. And \xrdef uses it to construct the % lists of floats. % \edef\thissection{\floatmagic=\safefloattype}% \setref{\floatlabel}{Yfloat}% }% \fi % % start with \parskip glue, I guess. \vskip\parskip % % Don't suppress indentation if a float happens to start a section. \restorefirstparagraphindent } % we have these possibilities: % @float Foo,lbl & @caption{Cap}: Foo 1.1: Cap % @float Foo,lbl & no caption: Foo 1.1 % @float Foo & @caption{Cap}: Foo: Cap % @float Foo & no caption: Foo % @float ,lbl & Caption{Cap}: 1.1: Cap % @float ,lbl & no caption: 1.1 % @float & @caption{Cap}: Cap % @float & no caption: % \def\Efloat{% \let\floatident = \empty % % In all cases, if we have a float type, it comes first. \ifx\floattype\empty \else \def\floatident{\floattype}\fi % % If we have an xref label, the number comes next. \ifx\floatlabel\empty \else \ifx\floattype\empty \else % if also had float type, need tie first. \appendtomacro\floatident{\tie}% \fi % the number. \appendtomacro\floatident{\chaplevelprefix\the\floatno}% \fi % % Start the printed caption with what we've constructed in % \floatident, but keep it separate; we need \floatident again. \let\captionline = \floatident % \ifx\thiscaption\empty \else \ifx\floatident\empty \else \appendtomacro\captionline{: }% had ident, so need a colon between \fi % % caption text. \appendtomacro\captionline{\scanexp\thiscaption}% \fi % % If we have anything to print, print it, with space before. % Eventually this needs to become an \insert. \ifx\captionline\empty \else \vskip.5\parskip \captionline % % Space below caption. \vskip\parskip \fi % % If have an xref label, write the list of floats info. Do this % after the caption, to avoid chance of it being a breakpoint. \ifx\floatlabel\empty \else % Write the text that goes in the lof to the aux file as % \floatlabel-lof. Besides \floatident, we include the short % caption if specified, else the full caption if specified, else nothing. {% \atdummies % % since we read the caption text in the macro world, where ^^M % is turned into a normal character, we have to scan it back, so % we don't write the literal three characters "^^M" into the aux file. \scanexp{% \xdef\noexpand\gtemp{% \ifx\thisshortcaption\empty \thiscaption \else \thisshortcaption \fi }% }% \immediate\write\auxfile{@xrdef{\floatlabel-lof}{\floatident \ifx\gtemp\empty \else : \gtemp \fi}}% }% \fi \egroup % end of \vtop % % place the captured inserts % % BEWARE: when the floats start floating, we have to issue warning % whenever an insert appears inside a float which could possibly % float. --kasal, 26may04 % \checkinserts } % Append the tokens #2 to the definition of macro #1, not expanding either. % \def\appendtomacro#1#2{% \expandafter\def\expandafter#1\expandafter{#1#2}% } % @caption, @shortcaption % \def\caption{\docaption\thiscaption} \def\shortcaption{\docaption\thisshortcaption} \def\docaption{\checkenv\float \bgroup\scanargctxt\defcaption} \def\defcaption#1#2{\egroup \def#1{#2}} % The parameter is the control sequence identifying the counter we are % going to use. Create it if it doesn't exist and assign it to \floatno. \def\getfloatno#1{% \ifx#1\relax % Haven't seen this figure type before. \csname newcount\endcsname #1% % % Remember to reset this floatno at the next chap. \expandafter\gdef\expandafter\resetallfloatnos \expandafter{\resetallfloatnos #1=0 }% \fi \let\floatno#1% } % \setref calls this to get the XREFLABEL-snt value. We want an @xref % to the FLOATLABEL to expand to "Figure 3.1". We call \setref when we % first read the @float command. % \def\Yfloat{\floattype@tie \chaplevelprefix\the\floatno}% % Magic string used for the XREFLABEL-title value, so \xrefX can % distinguish floats from other xref types. \def\floatmagic{!!float!!} % #1 is the control sequence we are passed; we expand into a conditional % which is true if #1 represents a float ref. That is, the magic % \thissection value which we \setref above. % \def\iffloat#1{\expandafter\doiffloat#1==\finish} % % #1 is (maybe) the \floatmagic string. If so, #2 will be the % (safe) float type for this float. We set \iffloattype to #2. % \def\doiffloat#1=#2=#3\finish{% \def\temp{#1}% \def\iffloattype{#2}% \ifx\temp\floatmagic } % @listoffloats FLOATTYPE - print a list of floats like a table of contents. % \parseargdef\listoffloats{% \def\floattype{#1}% floattype {% % the floattype might have accents or other special characters, % but we need to use it in a control sequence name. \indexnofonts \turnoffactive \xdef\safefloattype{\floattype}% }% % % \xrdef saves the floats as a \do-list in \floatlistSAFEFLOATTYPE. \expandafter\ifx\csname floatlist\safefloattype\endcsname \relax \ifhavexrefs % if the user said @listoffloats foo but never @float foo. \message{\linenumber No `\safefloattype' floats to list.}% \fi \else \begingroup \leftskip=\tocindent % indent these entries like a toc \let\do=\listoffloatsdo \csname floatlist\safefloattype\endcsname \endgroup \fi } % This is called on each entry in a list of floats. We're passed the % xref label, in the form LABEL-title, which is how we save it in the % aux file. We strip off the -title and look up \XRLABEL-lof, which % has the text we're supposed to typeset here. % % Figures without xref labels will not be included in the list (since % they won't appear in the aux file). % \def\listoffloatsdo#1{\listoffloatsdoentry#1\finish} \def\listoffloatsdoentry#1-title\finish{{% % Can't fully expand XR#1-lof because it can contain anything. Just % pass the control sequence. On the other hand, XR#1-pg is just the % page number, and we want to fully expand that so we can get a link % in pdf output. \toksA = \expandafter{\csname XR#1-lof\endcsname}% % % use the same \entry macro we use to generate the TOC and index. \edef\writeentry{\noexpand\entry{\the\toksA}{\csname XR#1-pg\endcsname}}% \writeentry }} \message{localization,} % @documentlanguage is usually given very early, just after % @setfilename. If done too late, it may not override everything % properly. Single argument is the language abbreviation. % It would be nice if we could set up a hyphenation file here. % \parseargdef\documentlanguage{% \tex % read txi-??.tex file in plain TeX. % Read the file if it exists. \openin 1 txi-#1.tex \ifeof 1 \errhelp = \nolanghelp \errmessage{Cannot read language file txi-#1.tex}% \else \input txi-#1.tex \fi \closein 1 \endgroup } \newhelp\nolanghelp{The given language definition file cannot be found or is empty. Maybe you need to install it? In the current directory should work if nowhere else does.} % Set the catcode of characters 128 through 255 to the specified number. % \def\setnonasciicharscatcode#1{% \count255=128 \loop\ifnum\count255<256 \global\catcode\count255=#1 \advance\count255 by 1 \repeat } % @documentencoding sets the definition of non-ASCII characters % according to the specified encoding. % \parseargdef\documentencoding{% % Encoding being declared for the document. \def\declaredencoding{\csname #1.enc\endcsname}% % % Supported encodings: names converted to tokens in order to be able % to compare them with \ifx. \def\ascii{\csname US-ASCII.enc\endcsname}% \def\latnine{\csname ISO-8859-15.enc\endcsname}% \def\latone{\csname ISO-8859-1.enc\endcsname}% \def\lattwo{\csname ISO-8859-2.enc\endcsname}% \def\utfeight{\csname UTF-8.enc\endcsname}% % \ifx \declaredencoding \ascii \asciichardefs % \else \ifx \declaredencoding \lattwo \setnonasciicharscatcode\active \lattwochardefs % \else \ifx \declaredencoding \latone \setnonasciicharscatcode\active \latonechardefs % \else \ifx \declaredencoding \latnine \setnonasciicharscatcode\active \latninechardefs % \else \ifx \declaredencoding \utfeight \setnonasciicharscatcode\active \utfeightchardefs % \else \message{Unknown document encoding #1, ignoring.}% % \fi % utfeight \fi % latnine \fi % latone \fi % lattwo \fi % ascii } % A message to be logged when using a character that isn't available % the default font encoding (OT1). % \def\missingcharmsg#1{\message{Character missing in OT1 encoding: #1.}} % Take account of \c (plain) vs. \, (Texinfo) difference. \def\cedilla#1{\ifx\c\ptexc\c{#1}\else\,{#1}\fi} % First, make active non-ASCII characters in order for them to be % correctly categorized when TeX reads the replacement text of % macros containing the character definitions. \setnonasciicharscatcode\active % % Latin1 (ISO-8859-1) character definitions. \def\latonechardefs{% \gdef^^a0{~} \gdef^^a1{\exclamdown} \gdef^^a2{\missingcharmsg{CENT SIGN}} \gdef^^a3{{\pounds}} \gdef^^a4{\missingcharmsg{CURRENCY SIGN}} \gdef^^a5{\missingcharmsg{YEN SIGN}} \gdef^^a6{\missingcharmsg{BROKEN BAR}} \gdef^^a7{\S} \gdef^^a8{\"{}} \gdef^^a9{\copyright} \gdef^^aa{\ordf} \gdef^^ab{\missingcharmsg{LEFT-POINTING DOUBLE ANGLE QUOTATION MARK}} \gdef^^ac{$\lnot$} \gdef^^ad{\-} \gdef^^ae{\registeredsymbol} \gdef^^af{\={}} % \gdef^^b0{\textdegree} \gdef^^b1{$\pm$} \gdef^^b2{$^2$} \gdef^^b3{$^3$} \gdef^^b4{\'{}} \gdef^^b5{$\mu$} \gdef^^b6{\P} % \gdef^^b7{$^.$} \gdef^^b8{\cedilla\ } \gdef^^b9{$^1$} \gdef^^ba{\ordm} % \gdef^^bb{\missingcharmsg{RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK}} \gdef^^bc{$1\over4$} \gdef^^bd{$1\over2$} \gdef^^be{$3\over4$} \gdef^^bf{\questiondown} % \gdef^^c0{\`A} \gdef^^c1{\'A} \gdef^^c2{\^A} \gdef^^c3{\~A} \gdef^^c4{\"A} \gdef^^c5{\ringaccent A} \gdef^^c6{\AE} \gdef^^c7{\cedilla C} \gdef^^c8{\`E} \gdef^^c9{\'E} \gdef^^ca{\^E} \gdef^^cb{\"E} \gdef^^cc{\`I} \gdef^^cd{\'I} \gdef^^ce{\^I} \gdef^^cf{\"I} % \gdef^^d0{\missingcharmsg{LATIN CAPITAL LETTER ETH}} \gdef^^d1{\~N} \gdef^^d2{\`O} \gdef^^d3{\'O} \gdef^^d4{\^O} \gdef^^d5{\~O} \gdef^^d6{\"O} \gdef^^d7{$\times$} \gdef^^d8{\O} \gdef^^d9{\`U} \gdef^^da{\'U} \gdef^^db{\^U} \gdef^^dc{\"U} \gdef^^dd{\'Y} \gdef^^de{\missingcharmsg{LATIN CAPITAL LETTER THORN}} \gdef^^df{\ss} % \gdef^^e0{\`a} \gdef^^e1{\'a} \gdef^^e2{\^a} \gdef^^e3{\~a} \gdef^^e4{\"a} \gdef^^e5{\ringaccent a} \gdef^^e6{\ae} \gdef^^e7{\cedilla c} \gdef^^e8{\`e} \gdef^^e9{\'e} \gdef^^ea{\^e} \gdef^^eb{\"e} \gdef^^ec{\`{\dotless i}} \gdef^^ed{\'{\dotless i}} \gdef^^ee{\^{\dotless i}} \gdef^^ef{\"{\dotless i}} % \gdef^^f0{\missingcharmsg{LATIN SMALL LETTER ETH}} \gdef^^f1{\~n} \gdef^^f2{\`o} \gdef^^f3{\'o} \gdef^^f4{\^o} \gdef^^f5{\~o} \gdef^^f6{\"o} \gdef^^f7{$\div$} \gdef^^f8{\o} \gdef^^f9{\`u} \gdef^^fa{\'u} \gdef^^fb{\^u} \gdef^^fc{\"u} \gdef^^fd{\'y} \gdef^^fe{\missingcharmsg{LATIN SMALL LETTER THORN}} \gdef^^ff{\"y} } % Latin9 (ISO-8859-15) encoding character definitions. \def\latninechardefs{% % Encoding is almost identical to Latin1. \latonechardefs % \gdef^^a4{\euro} \gdef^^a6{\v S} \gdef^^a8{\v s} \gdef^^b4{\v Z} \gdef^^b8{\v z} \gdef^^bc{\OE} \gdef^^bd{\oe} \gdef^^be{\"Y} } % Latin2 (ISO-8859-2) character definitions. \def\lattwochardefs{% \gdef^^a0{~} \gdef^^a1{\missingcharmsg{LATIN CAPITAL LETTER A WITH OGONEK}} \gdef^^a2{\u{}} \gdef^^a3{\L} \gdef^^a4{\missingcharmsg{CURRENCY SIGN}} \gdef^^a5{\v L} \gdef^^a6{\'S} \gdef^^a7{\S} \gdef^^a8{\"{}} \gdef^^a9{\v S} \gdef^^aa{\cedilla S} \gdef^^ab{\v T} \gdef^^ac{\'Z} \gdef^^ad{\-} \gdef^^ae{\v Z} \gdef^^af{\dotaccent Z} % \gdef^^b0{\textdegree} \gdef^^b1{\missingcharmsg{LATIN SMALL LETTER A WITH OGONEK}} \gdef^^b2{\missingcharmsg{OGONEK}} \gdef^^b3{\l} \gdef^^b4{\'{}} \gdef^^b5{\v l} \gdef^^b6{\'s} \gdef^^b7{\v{}} \gdef^^b8{\cedilla\ } \gdef^^b9{\v s} \gdef^^ba{\cedilla s} \gdef^^bb{\v t} \gdef^^bc{\'z} \gdef^^bd{\H{}} \gdef^^be{\v z} \gdef^^bf{\dotaccent z} % \gdef^^c0{\'R} \gdef^^c1{\'A} \gdef^^c2{\^A} \gdef^^c3{\u A} \gdef^^c4{\"A} \gdef^^c5{\'L} \gdef^^c6{\'C} \gdef^^c7{\cedilla C} \gdef^^c8{\v C} \gdef^^c9{\'E} \gdef^^ca{\missingcharmsg{LATIN CAPITAL LETTER E WITH OGONEK}} \gdef^^cb{\"E} \gdef^^cc{\v E} \gdef^^cd{\'I} \gdef^^ce{\^I} \gdef^^cf{\v D} % \gdef^^d0{\missingcharmsg{LATIN CAPITAL LETTER D WITH STROKE}} \gdef^^d1{\'N} \gdef^^d2{\v N} \gdef^^d3{\'O} \gdef^^d4{\^O} \gdef^^d5{\H O} \gdef^^d6{\"O} \gdef^^d7{$\times$} \gdef^^d8{\v R} \gdef^^d9{\ringaccent U} \gdef^^da{\'U} \gdef^^db{\H U} \gdef^^dc{\"U} \gdef^^dd{\'Y} \gdef^^de{\cedilla T} \gdef^^df{\ss} % \gdef^^e0{\'r} \gdef^^e1{\'a} \gdef^^e2{\^a} \gdef^^e3{\u a} \gdef^^e4{\"a} \gdef^^e5{\'l} \gdef^^e6{\'c} \gdef^^e7{\cedilla c} \gdef^^e8{\v c} \gdef^^e9{\'e} \gdef^^ea{\missingcharmsg{LATIN SMALL LETTER E WITH OGONEK}} \gdef^^eb{\"e} \gdef^^ec{\v e} \gdef^^ed{\'\i} \gdef^^ee{\^\i} \gdef^^ef{\v d} % \gdef^^f0{\missingcharmsg{LATIN SMALL LETTER D WITH STROKE}} \gdef^^f1{\'n} \gdef^^f2{\v n} \gdef^^f3{\'o} \gdef^^f4{\^o} \gdef^^f5{\H o} \gdef^^f6{\"o} \gdef^^f7{$\div$} \gdef^^f8{\v r} \gdef^^f9{\ringaccent u} \gdef^^fa{\'u} \gdef^^fb{\H u} \gdef^^fc{\"u} \gdef^^fd{\'y} \gdef^^fe{\cedilla t} \gdef^^ff{\dotaccent{}} } % UTF-8 character definitions. % % This code to support UTF-8 is based on LaTeX's utf8.def, with some % changes for Texinfo conventions. It is included here under the GPL by % permission from Frank Mittelbach and the LaTeX team. % \newcount\countUTFx \newcount\countUTFy \newcount\countUTFz \gdef\UTFviiiTwoOctets#1#2{\expandafter \UTFviiiDefined\csname u8:#1\string #2\endcsname} % \gdef\UTFviiiThreeOctets#1#2#3{\expandafter \UTFviiiDefined\csname u8:#1\string #2\string #3\endcsname} % \gdef\UTFviiiFourOctets#1#2#3#4{\expandafter \UTFviiiDefined\csname u8:#1\string #2\string #3\string #4\endcsname} \gdef\UTFviiiDefined#1{% \ifx #1\relax \message{\linenumber Unicode char \string #1 not defined for Texinfo}% \else \expandafter #1% \fi } \begingroup \catcode`\~13 \catcode`\"12 \def\UTFviiiLoop{% \global\catcode\countUTFx\active \uccode`\~\countUTFx \uppercase\expandafter{\UTFviiiTmp}% \advance\countUTFx by 1 \ifnum\countUTFx < \countUTFy \expandafter\UTFviiiLoop \fi} \countUTFx = "C2 \countUTFy = "E0 \def\UTFviiiTmp{% \xdef~{\noexpand\UTFviiiTwoOctets\string~}} \UTFviiiLoop \countUTFx = "E0 \countUTFy = "F0 \def\UTFviiiTmp{% \xdef~{\noexpand\UTFviiiThreeOctets\string~}} \UTFviiiLoop \countUTFx = "F0 \countUTFy = "F4 \def\UTFviiiTmp{% \xdef~{\noexpand\UTFviiiFourOctets\string~}} \UTFviiiLoop \endgroup \begingroup \catcode`\"=12 \catcode`\<=12 \catcode`\.=12 \catcode`\,=12 \catcode`\;=12 \catcode`\!=12 \catcode`\~=13 \gdef\DeclareUnicodeCharacter#1#2{% \countUTFz = "#1\relax \wlog{\space\space defining Unicode char U+#1 (decimal \the\countUTFz)}% \begingroup \parseXMLCharref \def\UTFviiiTwoOctets##1##2{% \csname u8:##1\string ##2\endcsname}% \def\UTFviiiThreeOctets##1##2##3{% \csname u8:##1\string ##2\string ##3\endcsname}% \def\UTFviiiFourOctets##1##2##3##4{% \csname u8:##1\string ##2\string ##3\string ##4\endcsname}% \expandafter\expandafter\expandafter\expandafter \expandafter\expandafter\expandafter \gdef\UTFviiiTmp{#2}% \endgroup} \gdef\parseXMLCharref{% \ifnum\countUTFz < "A0\relax \errhelp = \EMsimple \errmessage{Cannot define Unicode char value < 00A0}% \else\ifnum\countUTFz < "800\relax \parseUTFviiiA,% \parseUTFviiiB C\UTFviiiTwoOctets.,% \else\ifnum\countUTFz < "10000\relax \parseUTFviiiA;% \parseUTFviiiA,% \parseUTFviiiB E\UTFviiiThreeOctets.{,;}% \else \parseUTFviiiA;% \parseUTFviiiA,% \parseUTFviiiA!% \parseUTFviiiB F\UTFviiiFourOctets.{!,;}% \fi\fi\fi } \gdef\parseUTFviiiA#1{% \countUTFx = \countUTFz \divide\countUTFz by 64 \countUTFy = \countUTFz \multiply\countUTFz by 64 \advance\countUTFx by -\countUTFz \advance\countUTFx by 128 \uccode `#1\countUTFx \countUTFz = \countUTFy} \gdef\parseUTFviiiB#1#2#3#4{% \advance\countUTFz by "#10\relax \uccode `#3\countUTFz \uppercase{\gdef\UTFviiiTmp{#2#3#4}}} \endgroup \def\utfeightchardefs{% \DeclareUnicodeCharacter{00A0}{\tie} \DeclareUnicodeCharacter{00A1}{\exclamdown} \DeclareUnicodeCharacter{00A3}{\pounds} \DeclareUnicodeCharacter{00A8}{\"{ }} \DeclareUnicodeCharacter{00A9}{\copyright} \DeclareUnicodeCharacter{00AA}{\ordf} \DeclareUnicodeCharacter{00AD}{\-} \DeclareUnicodeCharacter{00AE}{\registeredsymbol} \DeclareUnicodeCharacter{00AF}{\={ }} \DeclareUnicodeCharacter{00B0}{\ringaccent{ }} \DeclareUnicodeCharacter{00B4}{\'{ }} \DeclareUnicodeCharacter{00B8}{\cedilla{ }} \DeclareUnicodeCharacter{00BA}{\ordm} \DeclareUnicodeCharacter{00BF}{\questiondown} \DeclareUnicodeCharacter{00C0}{\`A} \DeclareUnicodeCharacter{00C1}{\'A} \DeclareUnicodeCharacter{00C2}{\^A} \DeclareUnicodeCharacter{00C3}{\~A} \DeclareUnicodeCharacter{00C4}{\"A} \DeclareUnicodeCharacter{00C5}{\AA} \DeclareUnicodeCharacter{00C6}{\AE} \DeclareUnicodeCharacter{00C7}{\cedilla{C}} \DeclareUnicodeCharacter{00C8}{\`E} \DeclareUnicodeCharacter{00C9}{\'E} \DeclareUnicodeCharacter{00CA}{\^E} \DeclareUnicodeCharacter{00CB}{\"E} \DeclareUnicodeCharacter{00CC}{\`I} \DeclareUnicodeCharacter{00CD}{\'I} \DeclareUnicodeCharacter{00CE}{\^I} \DeclareUnicodeCharacter{00CF}{\"I} \DeclareUnicodeCharacter{00D1}{\~N} \DeclareUnicodeCharacter{00D2}{\`O} \DeclareUnicodeCharacter{00D3}{\'O} \DeclareUnicodeCharacter{00D4}{\^O} \DeclareUnicodeCharacter{00D5}{\~O} \DeclareUnicodeCharacter{00D6}{\"O} \DeclareUnicodeCharacter{00D8}{\O} \DeclareUnicodeCharacter{00D9}{\`U} \DeclareUnicodeCharacter{00DA}{\'U} \DeclareUnicodeCharacter{00DB}{\^U} \DeclareUnicodeCharacter{00DC}{\"U} \DeclareUnicodeCharacter{00DD}{\'Y} \DeclareUnicodeCharacter{00DF}{\ss} \DeclareUnicodeCharacter{00E0}{\`a} \DeclareUnicodeCharacter{00E1}{\'a} \DeclareUnicodeCharacter{00E2}{\^a} \DeclareUnicodeCharacter{00E3}{\~a} \DeclareUnicodeCharacter{00E4}{\"a} \DeclareUnicodeCharacter{00E5}{\aa} \DeclareUnicodeCharacter{00E6}{\ae} \DeclareUnicodeCharacter{00E7}{\cedilla{c}} \DeclareUnicodeCharacter{00E8}{\`e} \DeclareUnicodeCharacter{00E9}{\'e} \DeclareUnicodeCharacter{00EA}{\^e} \DeclareUnicodeCharacter{00EB}{\"e} \DeclareUnicodeCharacter{00EC}{\`{\dotless{i}}} \DeclareUnicodeCharacter{00ED}{\'{\dotless{i}}} \DeclareUnicodeCharacter{00EE}{\^{\dotless{i}}} \DeclareUnicodeCharacter{00EF}{\"{\dotless{i}}} \DeclareUnicodeCharacter{00F1}{\~n} \DeclareUnicodeCharacter{00F2}{\`o} \DeclareUnicodeCharacter{00F3}{\'o} \DeclareUnicodeCharacter{00F4}{\^o} \DeclareUnicodeCharacter{00F5}{\~o} \DeclareUnicodeCharacter{00F6}{\"o} \DeclareUnicodeCharacter{00F8}{\o} \DeclareUnicodeCharacter{00F9}{\`u} \DeclareUnicodeCharacter{00FA}{\'u} \DeclareUnicodeCharacter{00FB}{\^u} \DeclareUnicodeCharacter{00FC}{\"u} \DeclareUnicodeCharacter{00FD}{\'y} \DeclareUnicodeCharacter{00FF}{\"y} \DeclareUnicodeCharacter{0100}{\=A} \DeclareUnicodeCharacter{0101}{\=a} \DeclareUnicodeCharacter{0102}{\u{A}} \DeclareUnicodeCharacter{0103}{\u{a}} \DeclareUnicodeCharacter{0106}{\'C} \DeclareUnicodeCharacter{0107}{\'c} \DeclareUnicodeCharacter{0108}{\^C} \DeclareUnicodeCharacter{0109}{\^c} \DeclareUnicodeCharacter{010A}{\dotaccent{C}} \DeclareUnicodeCharacter{010B}{\dotaccent{c}} \DeclareUnicodeCharacter{010C}{\v{C}} \DeclareUnicodeCharacter{010D}{\v{c}} \DeclareUnicodeCharacter{010E}{\v{D}} \DeclareUnicodeCharacter{0112}{\=E} \DeclareUnicodeCharacter{0113}{\=e} \DeclareUnicodeCharacter{0114}{\u{E}} \DeclareUnicodeCharacter{0115}{\u{e}} \DeclareUnicodeCharacter{0116}{\dotaccent{E}} \DeclareUnicodeCharacter{0117}{\dotaccent{e}} \DeclareUnicodeCharacter{011A}{\v{E}} \DeclareUnicodeCharacter{011B}{\v{e}} \DeclareUnicodeCharacter{011C}{\^G} \DeclareUnicodeCharacter{011D}{\^g} \DeclareUnicodeCharacter{011E}{\u{G}} \DeclareUnicodeCharacter{011F}{\u{g}} \DeclareUnicodeCharacter{0120}{\dotaccent{G}} \DeclareUnicodeCharacter{0121}{\dotaccent{g}} \DeclareUnicodeCharacter{0124}{\^H} \DeclareUnicodeCharacter{0125}{\^h} \DeclareUnicodeCharacter{0128}{\~I} \DeclareUnicodeCharacter{0129}{\~{\dotless{i}}} \DeclareUnicodeCharacter{012A}{\=I} \DeclareUnicodeCharacter{012B}{\={\dotless{i}}} \DeclareUnicodeCharacter{012C}{\u{I}} \DeclareUnicodeCharacter{012D}{\u{\dotless{i}}} \DeclareUnicodeCharacter{0130}{\dotaccent{I}} \DeclareUnicodeCharacter{0131}{\dotless{i}} \DeclareUnicodeCharacter{0132}{IJ} \DeclareUnicodeCharacter{0133}{ij} \DeclareUnicodeCharacter{0134}{\^J} \DeclareUnicodeCharacter{0135}{\^{\dotless{j}}} \DeclareUnicodeCharacter{0139}{\'L} \DeclareUnicodeCharacter{013A}{\'l} \DeclareUnicodeCharacter{0141}{\L} \DeclareUnicodeCharacter{0142}{\l} \DeclareUnicodeCharacter{0143}{\'N} \DeclareUnicodeCharacter{0144}{\'n} \DeclareUnicodeCharacter{0147}{\v{N}} \DeclareUnicodeCharacter{0148}{\v{n}} \DeclareUnicodeCharacter{014C}{\=O} \DeclareUnicodeCharacter{014D}{\=o} \DeclareUnicodeCharacter{014E}{\u{O}} \DeclareUnicodeCharacter{014F}{\u{o}} \DeclareUnicodeCharacter{0150}{\H{O}} \DeclareUnicodeCharacter{0151}{\H{o}} \DeclareUnicodeCharacter{0152}{\OE} \DeclareUnicodeCharacter{0153}{\oe} \DeclareUnicodeCharacter{0154}{\'R} \DeclareUnicodeCharacter{0155}{\'r} \DeclareUnicodeCharacter{0158}{\v{R}} \DeclareUnicodeCharacter{0159}{\v{r}} \DeclareUnicodeCharacter{015A}{\'S} \DeclareUnicodeCharacter{015B}{\'s} \DeclareUnicodeCharacter{015C}{\^S} \DeclareUnicodeCharacter{015D}{\^s} \DeclareUnicodeCharacter{015E}{\cedilla{S}} \DeclareUnicodeCharacter{015F}{\cedilla{s}} \DeclareUnicodeCharacter{0160}{\v{S}} \DeclareUnicodeCharacter{0161}{\v{s}} \DeclareUnicodeCharacter{0162}{\cedilla{t}} \DeclareUnicodeCharacter{0163}{\cedilla{T}} \DeclareUnicodeCharacter{0164}{\v{T}} \DeclareUnicodeCharacter{0168}{\~U} \DeclareUnicodeCharacter{0169}{\~u} \DeclareUnicodeCharacter{016A}{\=U} \DeclareUnicodeCharacter{016B}{\=u} \DeclareUnicodeCharacter{016C}{\u{U}} \DeclareUnicodeCharacter{016D}{\u{u}} \DeclareUnicodeCharacter{016E}{\ringaccent{U}} \DeclareUnicodeCharacter{016F}{\ringaccent{u}} \DeclareUnicodeCharacter{0170}{\H{U}} \DeclareUnicodeCharacter{0171}{\H{u}} \DeclareUnicodeCharacter{0174}{\^W} \DeclareUnicodeCharacter{0175}{\^w} \DeclareUnicodeCharacter{0176}{\^Y} \DeclareUnicodeCharacter{0177}{\^y} \DeclareUnicodeCharacter{0178}{\"Y} \DeclareUnicodeCharacter{0179}{\'Z} \DeclareUnicodeCharacter{017A}{\'z} \DeclareUnicodeCharacter{017B}{\dotaccent{Z}} \DeclareUnicodeCharacter{017C}{\dotaccent{z}} \DeclareUnicodeCharacter{017D}{\v{Z}} \DeclareUnicodeCharacter{017E}{\v{z}} \DeclareUnicodeCharacter{01C4}{D\v{Z}} \DeclareUnicodeCharacter{01C5}{D\v{z}} \DeclareUnicodeCharacter{01C6}{d\v{z}} \DeclareUnicodeCharacter{01C7}{LJ} \DeclareUnicodeCharacter{01C8}{Lj} \DeclareUnicodeCharacter{01C9}{lj} \DeclareUnicodeCharacter{01CA}{NJ} \DeclareUnicodeCharacter{01CB}{Nj} \DeclareUnicodeCharacter{01CC}{nj} \DeclareUnicodeCharacter{01CD}{\v{A}} \DeclareUnicodeCharacter{01CE}{\v{a}} \DeclareUnicodeCharacter{01CF}{\v{I}} \DeclareUnicodeCharacter{01D0}{\v{\dotless{i}}} \DeclareUnicodeCharacter{01D1}{\v{O}} \DeclareUnicodeCharacter{01D2}{\v{o}} \DeclareUnicodeCharacter{01D3}{\v{U}} \DeclareUnicodeCharacter{01D4}{\v{u}} \DeclareUnicodeCharacter{01E2}{\={\AE}} \DeclareUnicodeCharacter{01E3}{\={\ae}} \DeclareUnicodeCharacter{01E6}{\v{G}} \DeclareUnicodeCharacter{01E7}{\v{g}} \DeclareUnicodeCharacter{01E8}{\v{K}} \DeclareUnicodeCharacter{01E9}{\v{k}} \DeclareUnicodeCharacter{01F0}{\v{\dotless{j}}} \DeclareUnicodeCharacter{01F1}{DZ} \DeclareUnicodeCharacter{01F2}{Dz} \DeclareUnicodeCharacter{01F3}{dz} \DeclareUnicodeCharacter{01F4}{\'G} \DeclareUnicodeCharacter{01F5}{\'g} \DeclareUnicodeCharacter{01F8}{\`N} \DeclareUnicodeCharacter{01F9}{\`n} \DeclareUnicodeCharacter{01FC}{\'{\AE}} \DeclareUnicodeCharacter{01FD}{\'{\ae}} \DeclareUnicodeCharacter{01FE}{\'{\O}} \DeclareUnicodeCharacter{01FF}{\'{\o}} \DeclareUnicodeCharacter{021E}{\v{H}} \DeclareUnicodeCharacter{021F}{\v{h}} \DeclareUnicodeCharacter{0226}{\dotaccent{A}} \DeclareUnicodeCharacter{0227}{\dotaccent{a}} \DeclareUnicodeCharacter{0228}{\cedilla{E}} \DeclareUnicodeCharacter{0229}{\cedilla{e}} \DeclareUnicodeCharacter{022E}{\dotaccent{O}} \DeclareUnicodeCharacter{022F}{\dotaccent{o}} \DeclareUnicodeCharacter{0232}{\=Y} \DeclareUnicodeCharacter{0233}{\=y} \DeclareUnicodeCharacter{0237}{\dotless{j}} \DeclareUnicodeCharacter{1E02}{\dotaccent{B}} \DeclareUnicodeCharacter{1E03}{\dotaccent{b}} \DeclareUnicodeCharacter{1E04}{\udotaccent{B}} \DeclareUnicodeCharacter{1E05}{\udotaccent{b}} \DeclareUnicodeCharacter{1E06}{\ubaraccent{B}} \DeclareUnicodeCharacter{1E07}{\ubaraccent{b}} \DeclareUnicodeCharacter{1E0A}{\dotaccent{D}} \DeclareUnicodeCharacter{1E0B}{\dotaccent{d}} \DeclareUnicodeCharacter{1E0C}{\udotaccent{D}} \DeclareUnicodeCharacter{1E0D}{\udotaccent{d}} \DeclareUnicodeCharacter{1E0E}{\ubaraccent{D}} \DeclareUnicodeCharacter{1E0F}{\ubaraccent{d}} \DeclareUnicodeCharacter{1E1E}{\dotaccent{F}} \DeclareUnicodeCharacter{1E1F}{\dotaccent{f}} \DeclareUnicodeCharacter{1E20}{\=G} \DeclareUnicodeCharacter{1E21}{\=g} \DeclareUnicodeCharacter{1E22}{\dotaccent{H}} \DeclareUnicodeCharacter{1E23}{\dotaccent{h}} \DeclareUnicodeCharacter{1E24}{\udotaccent{H}} \DeclareUnicodeCharacter{1E25}{\udotaccent{h}} \DeclareUnicodeCharacter{1E26}{\"H} \DeclareUnicodeCharacter{1E27}{\"h} \DeclareUnicodeCharacter{1E30}{\'K} \DeclareUnicodeCharacter{1E31}{\'k} \DeclareUnicodeCharacter{1E32}{\udotaccent{K}} \DeclareUnicodeCharacter{1E33}{\udotaccent{k}} \DeclareUnicodeCharacter{1E34}{\ubaraccent{K}} \DeclareUnicodeCharacter{1E35}{\ubaraccent{k}} \DeclareUnicodeCharacter{1E36}{\udotaccent{L}} \DeclareUnicodeCharacter{1E37}{\udotaccent{l}} \DeclareUnicodeCharacter{1E3A}{\ubaraccent{L}} \DeclareUnicodeCharacter{1E3B}{\ubaraccent{l}} \DeclareUnicodeCharacter{1E3E}{\'M} \DeclareUnicodeCharacter{1E3F}{\'m} \DeclareUnicodeCharacter{1E40}{\dotaccent{M}} \DeclareUnicodeCharacter{1E41}{\dotaccent{m}} \DeclareUnicodeCharacter{1E42}{\udotaccent{M}} \DeclareUnicodeCharacter{1E43}{\udotaccent{m}} \DeclareUnicodeCharacter{1E44}{\dotaccent{N}} \DeclareUnicodeCharacter{1E45}{\dotaccent{n}} \DeclareUnicodeCharacter{1E46}{\udotaccent{N}} \DeclareUnicodeCharacter{1E47}{\udotaccent{n}} \DeclareUnicodeCharacter{1E48}{\ubaraccent{N}} \DeclareUnicodeCharacter{1E49}{\ubaraccent{n}} \DeclareUnicodeCharacter{1E54}{\'P} \DeclareUnicodeCharacter{1E55}{\'p} \DeclareUnicodeCharacter{1E56}{\dotaccent{P}} \DeclareUnicodeCharacter{1E57}{\dotaccent{p}} \DeclareUnicodeCharacter{1E58}{\dotaccent{R}} \DeclareUnicodeCharacter{1E59}{\dotaccent{r}} \DeclareUnicodeCharacter{1E5A}{\udotaccent{R}} \DeclareUnicodeCharacter{1E5B}{\udotaccent{r}} \DeclareUnicodeCharacter{1E5E}{\ubaraccent{R}} \DeclareUnicodeCharacter{1E5F}{\ubaraccent{r}} \DeclareUnicodeCharacter{1E60}{\dotaccent{S}} \DeclareUnicodeCharacter{1E61}{\dotaccent{s}} \DeclareUnicodeCharacter{1E62}{\udotaccent{S}} \DeclareUnicodeCharacter{1E63}{\udotaccent{s}} \DeclareUnicodeCharacter{1E6A}{\dotaccent{T}} \DeclareUnicodeCharacter{1E6B}{\dotaccent{t}} \DeclareUnicodeCharacter{1E6C}{\udotaccent{T}} \DeclareUnicodeCharacter{1E6D}{\udotaccent{t}} \DeclareUnicodeCharacter{1E6E}{\ubaraccent{T}} \DeclareUnicodeCharacter{1E6F}{\ubaraccent{t}} \DeclareUnicodeCharacter{1E7C}{\~V} \DeclareUnicodeCharacter{1E7D}{\~v} \DeclareUnicodeCharacter{1E7E}{\udotaccent{V}} \DeclareUnicodeCharacter{1E7F}{\udotaccent{v}} \DeclareUnicodeCharacter{1E80}{\`W} \DeclareUnicodeCharacter{1E81}{\`w} \DeclareUnicodeCharacter{1E82}{\'W} \DeclareUnicodeCharacter{1E83}{\'w} \DeclareUnicodeCharacter{1E84}{\"W} \DeclareUnicodeCharacter{1E85}{\"w} \DeclareUnicodeCharacter{1E86}{\dotaccent{W}} \DeclareUnicodeCharacter{1E87}{\dotaccent{w}} \DeclareUnicodeCharacter{1E88}{\udotaccent{W}} \DeclareUnicodeCharacter{1E89}{\udotaccent{w}} \DeclareUnicodeCharacter{1E8A}{\dotaccent{X}} \DeclareUnicodeCharacter{1E8B}{\dotaccent{x}} \DeclareUnicodeCharacter{1E8C}{\"X} \DeclareUnicodeCharacter{1E8D}{\"x} \DeclareUnicodeCharacter{1E8E}{\dotaccent{Y}} \DeclareUnicodeCharacter{1E8F}{\dotaccent{y}} \DeclareUnicodeCharacter{1E90}{\^Z} \DeclareUnicodeCharacter{1E91}{\^z} \DeclareUnicodeCharacter{1E92}{\udotaccent{Z}} \DeclareUnicodeCharacter{1E93}{\udotaccent{z}} \DeclareUnicodeCharacter{1E94}{\ubaraccent{Z}} \DeclareUnicodeCharacter{1E95}{\ubaraccent{z}} \DeclareUnicodeCharacter{1E96}{\ubaraccent{h}} \DeclareUnicodeCharacter{1E97}{\"t} \DeclareUnicodeCharacter{1E98}{\ringaccent{w}} \DeclareUnicodeCharacter{1E99}{\ringaccent{y}} \DeclareUnicodeCharacter{1EA0}{\udotaccent{A}} \DeclareUnicodeCharacter{1EA1}{\udotaccent{a}} \DeclareUnicodeCharacter{1EB8}{\udotaccent{E}} \DeclareUnicodeCharacter{1EB9}{\udotaccent{e}} \DeclareUnicodeCharacter{1EBC}{\~E} \DeclareUnicodeCharacter{1EBD}{\~e} \DeclareUnicodeCharacter{1ECA}{\udotaccent{I}} \DeclareUnicodeCharacter{1ECB}{\udotaccent{i}} \DeclareUnicodeCharacter{1ECC}{\udotaccent{O}} \DeclareUnicodeCharacter{1ECD}{\udotaccent{o}} \DeclareUnicodeCharacter{1EE4}{\udotaccent{U}} \DeclareUnicodeCharacter{1EE5}{\udotaccent{u}} \DeclareUnicodeCharacter{1EF2}{\`Y} \DeclareUnicodeCharacter{1EF3}{\`y} \DeclareUnicodeCharacter{1EF4}{\udotaccent{Y}} \DeclareUnicodeCharacter{1EF8}{\~Y} \DeclareUnicodeCharacter{1EF9}{\~y} \DeclareUnicodeCharacter{2013}{--} \DeclareUnicodeCharacter{2014}{---} \DeclareUnicodeCharacter{2022}{\bullet} \DeclareUnicodeCharacter{2026}{\dots} \DeclareUnicodeCharacter{20AC}{\euro} \DeclareUnicodeCharacter{2192}{\expansion} \DeclareUnicodeCharacter{21D2}{\result} \DeclareUnicodeCharacter{2212}{\minus} \DeclareUnicodeCharacter{2217}{\point} \DeclareUnicodeCharacter{2261}{\equiv} }% end of \utfeightchardefs % US-ASCII character definitions. \def\asciichardefs{% nothing need be done \relax } % Make non-ASCII characters printable again for compatibility with % existing Texinfo documents that may use them, even without declaring a % document encoding. % \setnonasciicharscatcode \other \message{formatting,} \newdimen\defaultparindent \defaultparindent = 15pt \chapheadingskip = 15pt plus 4pt minus 2pt \secheadingskip = 12pt plus 3pt minus 2pt \subsecheadingskip = 9pt plus 2pt minus 2pt % Prevent underfull vbox error messages. \vbadness = 10000 % Don't be so finicky about underfull hboxes, either. \hbadness = 2000 % Following George Bush, just get rid of widows and orphans. \widowpenalty=10000 \clubpenalty=10000 % Use TeX 3.0's \emergencystretch to help line breaking, but if we're % using an old version of TeX, don't do anything. We want the amount of % stretch added to depend on the line length, hence the dependence on % \hsize. We call this whenever the paper size is set. % \def\setemergencystretch{% \ifx\emergencystretch\thisisundefined % Allow us to assign to \emergencystretch anyway. \def\emergencystretch{\dimen0}% \else \emergencystretch = .15\hsize \fi } % Parameters in order: 1) textheight; 2) textwidth; % 3) voffset; 4) hoffset; 5) binding offset; 6) topskip; % 7) physical page height; 8) physical page width. % % We also call \setleading{\textleading}, so the caller should define % \textleading. The caller should also set \parskip. % \def\internalpagesizes#1#2#3#4#5#6#7#8{% \voffset = #3\relax \topskip = #6\relax \splittopskip = \topskip % \vsize = #1\relax \advance\vsize by \topskip \outervsize = \vsize \advance\outervsize by 2\topandbottommargin \pageheight = \vsize % \hsize = #2\relax \outerhsize = \hsize \advance\outerhsize by 0.5in \pagewidth = \hsize % \normaloffset = #4\relax \bindingoffset = #5\relax % \ifpdf \pdfpageheight #7\relax \pdfpagewidth #8\relax \fi % \setleading{\textleading} % \parindent = \defaultparindent \setemergencystretch } % @letterpaper (the default). \def\letterpaper{{\globaldefs = 1 \parskip = 3pt plus 2pt minus 1pt \textleading = 13.2pt % % If page is nothing but text, make it come out even. \internalpagesizes{46\baselineskip}{6in}% {\voffset}{.25in}% {\bindingoffset}{36pt}% {11in}{8.5in}% }} % Use @smallbook to reset parameters for 7x9.25 trim size. \def\smallbook{{\globaldefs = 1 \parskip = 2pt plus 1pt \textleading = 12pt % \internalpagesizes{7.5in}{5in}% {\voffset}{.25in}% {\bindingoffset}{16pt}% {9.25in}{7in}% % \lispnarrowing = 0.3in \tolerance = 700 \hfuzz = 1pt \contentsrightmargin = 0pt \defbodyindent = .5cm }} % Use @smallerbook to reset parameters for 6x9 trim size. % (Just testing, parameters still in flux.) \def\smallerbook{{\globaldefs = 1 \parskip = 1.5pt plus 1pt \textleading = 12pt % \internalpagesizes{7.4in}{4.8in}% {-.2in}{-.4in}% {0pt}{14pt}% {9in}{6in}% % \lispnarrowing = 0.25in \tolerance = 700 \hfuzz = 1pt \contentsrightmargin = 0pt \defbodyindent = .4cm }} % Use @afourpaper to print on European A4 paper. \def\afourpaper{{\globaldefs = 1 \parskip = 3pt plus 2pt minus 1pt \textleading = 13.2pt % % Double-side printing via postscript on Laserjet 4050 % prints double-sided nicely when \bindingoffset=10mm and \hoffset=-6mm. % To change the settings for a different printer or situation, adjust % \normaloffset until the front-side and back-side texts align. Then % do the same for \bindingoffset. You can set these for testing in % your texinfo source file like this: % @tex % \global\normaloffset = -6mm % \global\bindingoffset = 10mm % @end tex \internalpagesizes{51\baselineskip}{160mm} {\voffset}{\hoffset}% {\bindingoffset}{44pt}% {297mm}{210mm}% % \tolerance = 700 \hfuzz = 1pt \contentsrightmargin = 0pt \defbodyindent = 5mm }} % Use @afivepaper to print on European A5 paper. % From romildo@urano.iceb.ufop.br, 2 July 2000. % He also recommends making @example and @lisp be small. \def\afivepaper{{\globaldefs = 1 \parskip = 2pt plus 1pt minus 0.1pt \textleading = 12.5pt % \internalpagesizes{160mm}{120mm}% {\voffset}{\hoffset}% {\bindingoffset}{8pt}% {210mm}{148mm}% % \lispnarrowing = 0.2in \tolerance = 800 \hfuzz = 1.2pt \contentsrightmargin = 0pt \defbodyindent = 2mm \tableindent = 12mm }} % A specific text layout, 24x15cm overall, intended for A4 paper. \def\afourlatex{{\globaldefs = 1 \afourpaper \internalpagesizes{237mm}{150mm}% {\voffset}{4.6mm}% {\bindingoffset}{7mm}% {297mm}{210mm}% % % Must explicitly reset to 0 because we call \afourpaper. \globaldefs = 0 }} % Use @afourwide to print on A4 paper in landscape format. \def\afourwide{{\globaldefs = 1 \afourpaper \internalpagesizes{241mm}{165mm}% {\voffset}{-2.95mm}% {\bindingoffset}{7mm}% {297mm}{210mm}% \globaldefs = 0 }} % @pagesizes TEXTHEIGHT[,TEXTWIDTH] % Perhaps we should allow setting the margins, \topskip, \parskip, % and/or leading, also. Or perhaps we should compute them somehow. % \parseargdef\pagesizes{\pagesizesyyy #1,,\finish} \def\pagesizesyyy#1,#2,#3\finish{{% \setbox0 = \hbox{\ignorespaces #2}\ifdim\wd0 > 0pt \hsize=#2\relax \fi \globaldefs = 1 % \parskip = 3pt plus 2pt minus 1pt \setleading{\textleading}% % \dimen0 = #1 \advance\dimen0 by \voffset % \dimen2 = \hsize \advance\dimen2 by \normaloffset % \internalpagesizes{#1}{\hsize}% {\voffset}{\normaloffset}% {\bindingoffset}{44pt}% {\dimen0}{\dimen2}% }} % Set default to letter. % \letterpaper \message{and turning on texinfo input format.} % Define macros to output various characters with catcode for normal text. \catcode`\"=\other \catcode`\~=\other \catcode`\^=\other \catcode`\_=\other \catcode`\|=\other \catcode`\<=\other \catcode`\>=\other \catcode`\+=\other \catcode`\$=\other \def\normaldoublequote{"} \def\normaltilde{~} \def\normalcaret{^} \def\normalunderscore{_} \def\normalverticalbar{|} \def\normalless{<} \def\normalgreater{>} \def\normalplus{+} \def\normaldollar{$}%$ font-lock fix % This macro is used to make a character print one way in \tt % (where it can probably be output as-is), and another way in other fonts, % where something hairier probably needs to be done. % % #1 is what to print if we are indeed using \tt; #2 is what to print % otherwise. Since all the Computer Modern typewriter fonts have zero % interword stretch (and shrink), and it is reasonable to expect all % typewriter fonts to have this, we can check that font parameter. % \def\ifusingtt#1#2{\ifdim \fontdimen3\font=0pt #1\else #2\fi} % Same as above, but check for italic font. Actually this also catches % non-italic slanted fonts since it is impossible to distinguish them from % italic fonts. But since this is only used by $ and it uses \sl anyway % this is not a problem. \def\ifusingit#1#2{\ifdim \fontdimen1\font>0pt #1\else #2\fi} % Turn off all special characters except @ % (and those which the user can use as if they were ordinary). % Most of these we simply print from the \tt font, but for some, we can % use math or other variants that look better in normal text. \catcode`\"=\active \def\activedoublequote{{\tt\char34}} \let"=\activedoublequote \catcode`\~=\active \def~{{\tt\char126}} \chardef\hat=`\^ \catcode`\^=\active \def^{{\tt \hat}} \catcode`\_=\active \def_{\ifusingtt\normalunderscore\_} \let\realunder=_ % Subroutine for the previous macro. \def\_{\leavevmode \kern.07em \vbox{\hrule width.3em height.1ex}\kern .07em } \catcode`\|=\active \def|{{\tt\char124}} \chardef \less=`\< \catcode`\<=\active \def<{{\tt \less}} \chardef \gtr=`\> \catcode`\>=\active \def>{{\tt \gtr}} \catcode`\+=\active \def+{{\tt \char 43}} \catcode`\$=\active \def${\ifusingit{{\sl\$}}\normaldollar}%$ font-lock fix % If a .fmt file is being used, characters that might appear in a file % name cannot be active until we have parsed the command line. % So turn them off again, and have \everyjob (or @setfilename) turn them on. % \otherifyactive is called near the end of this file. \def\otherifyactive{\catcode`+=\other \catcode`\_=\other} % Used sometimes to turn off (effectively) the active characters even after % parsing them. \def\turnoffactive{% \normalturnoffactive \otherbackslash } \catcode`\@=0 % \backslashcurfont outputs one backslash character in current font, % as in \char`\\. \global\chardef\backslashcurfont=`\\ \global\let\rawbackslashxx=\backslashcurfont % let existing .??s files work % \realbackslash is an actual character `\' with catcode other, and % \doublebackslash is two of them (for the pdf outlines). {\catcode`\\=\other @gdef@realbackslash{\} @gdef@doublebackslash{\\}} % In texinfo, backslash is an active character; it prints the backslash % in fixed width font. \catcode`\\=\active @def@normalbackslash{{@tt@backslashcurfont}} % On startup, @fixbackslash assigns: % @let \ = @normalbackslash % \rawbackslash defines an active \ to do \backslashcurfont. % \otherbackslash defines an active \ to be a literal `\' character with % catcode other. @gdef@rawbackslash{@let\=@backslashcurfont} @gdef@otherbackslash{@let\=@realbackslash} % Same as @turnoffactive except outputs \ as {\tt\char`\\} instead of % the literal character `\'. % @def@normalturnoffactive{% @let\=@normalbackslash @let"=@normaldoublequote @let~=@normaltilde @let^=@normalcaret @let_=@normalunderscore @let|=@normalverticalbar @let<=@normalless @let>=@normalgreater @let+=@normalplus @let$=@normaldollar %$ font-lock fix @unsepspaces } % Make _ and + \other characters, temporarily. % This is canceled by @fixbackslash. @otherifyactive % If a .fmt file is being used, we don't want the `\input texinfo' to show up. % That is what \eatinput is for; after that, the `\' should revert to printing % a backslash. % @gdef@eatinput input texinfo{@fixbackslash} @global@let\ = @eatinput % On the other hand, perhaps the file did not have a `\input texinfo'. Then % the first `\' in the file would cause an error. This macro tries to fix % that, assuming it is called before the first `\' could plausibly occur. % Also turn back on active characters that might appear in the input % file name, in case not using a pre-dumped format. % @gdef@fixbackslash{% @ifx\@eatinput @let\ = @normalbackslash @fi @catcode`+=@active @catcode`@_=@active } % Say @foo, not \foo, in error messages. @escapechar = `@@ % These look ok in all fonts, so just make them not special. @catcode`@& = @other @catcode`@# = @other @catcode`@% = @other @c Local variables: @c eval: (add-hook 'write-file-hooks 'time-stamp) @c page-delimiter: "^\\\\message" @c time-stamp-start: "def\\\\texinfoversion{" @c time-stamp-format: "%:y-%02m-%02d.%02H" @c time-stamp-end: "}" @c End: @c vim:sw=2: @ignore arch-tag: e1b36e32-c96e-4135-a41a-0b2efa2ea115 @end ignore diff --git a/cipher/cipher-internal.h b/cipher/cipher-internal.h index ea9c33d3..b7481255 100644 --- a/cipher/cipher-internal.h +++ b/cipher/cipher-internal.h @@ -1,509 +1,509 @@ /* cipher-internal.h - Internal defs for cipher.c * Copyright (C) 2011 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 . */ #ifndef G10_CIPHER_INTERNAL_H #define G10_CIPHER_INTERNAL_H #include "./poly1305-internal.h" /* The maximum supported size of a block in bytes. */ #define MAX_BLOCKSIZE 16 /* The length for an OCB block. Although OCB supports any block length it does not make sense to use a 64 bit blocklen (and cipher) because this reduces the security margin to an unacceptable state. Thus we require a cipher with 128 bit blocklength. */ #define OCB_BLOCK_LEN (128/8) /* The size of the pre-computed L table for OCB. This takes the same size as the table used for GCM and thus we don't save anything by not using such a table. */ #define OCB_L_TABLE_SIZE 16 /* Check the above constants. */ #if OCB_BLOCK_LEN > MAX_BLOCKSIZE # error OCB_BLOCKLEN > MAX_BLOCKSIZE #endif /* Magic values for the context structure. */ #define CTX_MAGIC_NORMAL 0x24091964 #define CTX_MAGIC_SECURE 0x46919042 /* Try to use 16 byte aligned cipher context for better performance. We use the aligned attribute, thus it is only possible to implement this with gcc. */ #undef NEED_16BYTE_ALIGNED_CONTEXT #ifdef HAVE_GCC_ATTRIBUTE_ALIGNED # define NEED_16BYTE_ALIGNED_CONTEXT 1 #endif /* Undef this symbol to trade GCM speed for 256 bytes of memory per context */ #define GCM_USE_TABLES 1 /* GCM_USE_INTEL_PCLMUL indicates whether to compile GCM with Intel PCLMUL code. */ #undef GCM_USE_INTEL_PCLMUL #if defined(ENABLE_PCLMUL_SUPPORT) && defined(GCM_USE_TABLES) # if ((defined(__i386__) && SIZEOF_UNSIGNED_LONG == 4) || defined(__x86_64__)) # if __GNUC__ >= 4 # define GCM_USE_INTEL_PCLMUL 1 # endif # endif #endif /* GCM_USE_INTEL_PCLMUL */ /* GCM_USE_ARM_PMULL indicates whether to compile GCM with ARMv8 PMULL code. */ #undef GCM_USE_ARM_PMULL #if defined(ENABLE_ARM_CRYPTO_SUPPORT) && defined(GCM_USE_TABLES) # if defined(HAVE_ARM_ARCH_V6) && defined(__ARMEL__) \ && defined(HAVE_COMPATIBLE_GCC_ARM_PLATFORM_AS) \ && defined(HAVE_GCC_INLINE_ASM_AARCH32_CRYPTO) # define GCM_USE_ARM_PMULL 1 # elif defined(__AARCH64EL__) && \ defined(HAVE_COMPATIBLE_GCC_AARCH64_PLATFORM_AS) && \ defined(HAVE_GCC_INLINE_ASM_AARCH64_CRYPTO) # define GCM_USE_ARM_PMULL 1 # endif #endif /* GCM_USE_ARM_PMULL */ typedef unsigned int (*ghash_fn_t) (gcry_cipher_hd_t c, byte *result, const byte *buf, size_t nblocks); /* A VIA processor with the Padlock engine as well as the Intel AES_NI instructions require an alignment of most data on a 16 byte boundary. Because we trick out the compiler while allocating the context, the align attribute as used in rijndael.c does not work on its own. Thus we need to make sure that the entire context structure is a aligned on that boundary. We achieve this by defining a new type and use that instead of our usual alignment type. */ typedef union { PROPERLY_ALIGNED_TYPE foo; #ifdef NEED_16BYTE_ALIGNED_CONTEXT char bar[16] __attribute__ ((aligned (16))); #endif char c[1]; } cipher_context_alignment_t; /* The handle structure. */ struct gcry_cipher_handle { int magic; size_t actual_handle_size; /* Allocated size of this handle. */ size_t handle_offset; /* Offset to the malloced block. */ gcry_cipher_spec_t *spec; /* The algorithm id. This is a hack required because the module interface does not easily allow to retrieve this value. */ int algo; /* A structure with function pointers for bulk operations. Due to limitations of the module system (we don't want to change the API) we need to keep these function pointers here. The cipher - open function intializes them and the actual encryption routines + open function initializes them and the actual encryption routines use them if they are not NULL. */ struct { void (*cfb_enc)(void *context, unsigned char *iv, void *outbuf_arg, const void *inbuf_arg, size_t nblocks); void (*cfb_dec)(void *context, unsigned char *iv, void *outbuf_arg, const void *inbuf_arg, size_t nblocks); void (*cbc_enc)(void *context, unsigned char *iv, void *outbuf_arg, const void *inbuf_arg, size_t nblocks, int cbc_mac); void (*cbc_dec)(void *context, unsigned char *iv, void *outbuf_arg, const void *inbuf_arg, size_t nblocks); void (*ctr_enc)(void *context, unsigned char *iv, void *outbuf_arg, const void *inbuf_arg, size_t nblocks); size_t (*ocb_crypt)(gcry_cipher_hd_t c, void *outbuf_arg, const void *inbuf_arg, size_t nblocks, int encrypt); size_t (*ocb_auth)(gcry_cipher_hd_t c, const void *abuf_arg, size_t nblocks); void (*xts_crypt)(gcry_cipher_hd_t c, unsigned char *tweak, void *outbuf_arg, const void *inbuf_arg, size_t nblocks, int encrypt); } bulk; int mode; unsigned int flags; struct { unsigned int key:1; /* Set to 1 if a key has been set. */ unsigned int iv:1; /* Set to 1 if a IV has been set. */ unsigned int tag:1; /* Set to 1 if a tag is finalized. */ unsigned int finalize:1; /* Next encrypt/decrypt has the final data. */ } marks; /* The initialization vector. For best performance we make sure that it is properly aligned. In particular some implementations of bulk operations expect an 16 byte aligned IV. IV is also used to store CBC-MAC in CCM mode; counter IV is stored in U_CTR. For OCB mode it is used for the offset value. */ union { cipher_context_alignment_t iv_align; unsigned char iv[MAX_BLOCKSIZE]; } u_iv; /* The counter for CTR mode. This field is also used by AESWRAP and thus we can't use the U_IV union. For OCB mode it is used for the checksum. */ union { cipher_context_alignment_t iv_align; unsigned char ctr[MAX_BLOCKSIZE]; } u_ctr; /* Space to save an IV or CTR for chaining operations. */ unsigned char lastiv[MAX_BLOCKSIZE]; int unused; /* Number of unused bytes in LASTIV. */ union { /* Mode specific storage for CCM mode. */ struct { u64 encryptlen; u64 aadlen; unsigned int authlen; /* Space to save partial input lengths for MAC. */ unsigned char macbuf[GCRY_CCM_BLOCK_LEN]; int mac_unused; /* Number of unprocessed bytes in MACBUF. */ unsigned char s0[GCRY_CCM_BLOCK_LEN]; unsigned int nonce:1;/* Set to 1 if nonce has been set. */ unsigned int lengths:1; /* Set to 1 if CCM length parameters has been processed. */ } ccm; /* Mode specific storage for Poly1305 mode. */ struct { /* byte counter for AAD. */ u32 aadcount[2]; /* byte counter for data. */ u32 datacount[2]; unsigned int aad_finalized:1; unsigned int bytecount_over_limits:1; poly1305_context_t ctx; } poly1305; /* Mode specific storage for CMAC mode. */ struct { unsigned int tag:1; /* Set to 1 if tag has been finalized. */ /* Subkeys for tag creation, not cleared by gcry_cipher_reset. */ unsigned char subkeys[2][MAX_BLOCKSIZE]; } cmac; /* Mode specific storage for GCM mode. */ struct { /* The interim tag for GCM mode. */ union { cipher_context_alignment_t iv_align; unsigned char tag[MAX_BLOCKSIZE]; } u_tag; /* Space to save partial input lengths for MAC. */ unsigned char macbuf[GCRY_CCM_BLOCK_LEN]; int mac_unused; /* Number of unprocessed bytes in MACBUF. */ /* byte counters for GCM */ u32 aadlen[2]; u32 datalen[2]; /* encrypted tag counter */ unsigned char tagiv[MAX_BLOCKSIZE]; unsigned int ghash_data_finalized:1; unsigned int ghash_aad_finalized:1; unsigned int datalen_over_limits:1; unsigned int disallow_encryption_because_of_setiv_in_fips_mode:1; /* --- Following members are not cleared in gcry_cipher_reset --- */ /* GHASH multiplier from key. */ union { cipher_context_alignment_t iv_align; unsigned char key[MAX_BLOCKSIZE]; } u_ghash_key; /* GHASH implementation in use. */ ghash_fn_t ghash_fn; /* Pre-calculated table for GCM. */ #ifdef GCM_USE_TABLES #if (SIZEOF_UNSIGNED_LONG == 8 || defined(__x86_64__)) #define GCM_TABLES_USE_U64 1 u64 gcm_table[2 * 16]; #else #undef GCM_TABLES_USE_U64 u32 gcm_table[4 * 16]; #endif #endif } gcm; /* Mode specific storage for OCB mode. */ struct { /* Helper variables and pre-computed table of L values. */ unsigned char L_star[OCB_BLOCK_LEN]; unsigned char L_dollar[OCB_BLOCK_LEN]; unsigned char L[OCB_BLOCK_LEN][OCB_L_TABLE_SIZE]; /* The tag is valid if marks.tag has been set. */ unsigned char tag[OCB_BLOCK_LEN]; /* A buffer to hold the offset for the AAD processing. */ unsigned char aad_offset[OCB_BLOCK_LEN]; /* A buffer to hold the current sum of AAD processing. We can't use tag here because tag may already hold the preprocessed checksum of the data. */ unsigned char aad_sum[OCB_BLOCK_LEN]; /* A buffer to store AAD data not yet processed. */ unsigned char aad_leftover[OCB_BLOCK_LEN]; /* Number of data/aad blocks processed so far. */ u64 data_nblocks; u64 aad_nblocks; /* Number of valid bytes in AAD_LEFTOVER. */ unsigned char aad_nleftover; /* Length of the tag. Fixed for now but may eventually be specified using a set of gcry_cipher_flags. */ unsigned char taglen; /* Flags indicating that the final data/aad block has been processed. */ unsigned int data_finalized:1; unsigned int aad_finalized:1; } ocb; /* Mode specific storage for XTS mode. */ struct { /* Pointer to tweak cipher context, allocated after actual * cipher context. */ char *tweak_context; } xts; } u_mode; /* What follows are two contexts of the cipher in use. The first one needs to be aligned well enough for the cipher operation whereas the second one is a copy created by cipher_setkey and used by cipher_reset. That second copy has no need for proper aligment because it is only accessed by memcpy. */ cipher_context_alignment_t context; }; /*-- cipher-cbc.c --*/ gcry_err_code_t _gcry_cipher_cbc_encrypt /* */ (gcry_cipher_hd_t c, unsigned char *outbuf, size_t outbuflen, const unsigned char *inbuf, size_t inbuflen); gcry_err_code_t _gcry_cipher_cbc_decrypt /* */ (gcry_cipher_hd_t c, unsigned char *outbuf, size_t outbuflen, const unsigned char *inbuf, size_t inbuflen); /*-- cipher-cfb.c --*/ gcry_err_code_t _gcry_cipher_cfb_encrypt /* */ (gcry_cipher_hd_t c, unsigned char *outbuf, size_t outbuflen, const unsigned char *inbuf, size_t inbuflen); gcry_err_code_t _gcry_cipher_cfb_decrypt /* */ (gcry_cipher_hd_t c, unsigned char *outbuf, size_t outbuflen, const unsigned char *inbuf, size_t inbuflen); gcry_err_code_t _gcry_cipher_cfb8_encrypt /* */ (gcry_cipher_hd_t c, unsigned char *outbuf, size_t outbuflen, const unsigned char *inbuf, size_t inbuflen); gcry_err_code_t _gcry_cipher_cfb8_decrypt /* */ (gcry_cipher_hd_t c, unsigned char *outbuf, size_t outbuflen, const unsigned char *inbuf, size_t inbuflen); /*-- cipher-ofb.c --*/ gcry_err_code_t _gcry_cipher_ofb_encrypt /* */ (gcry_cipher_hd_t c, unsigned char *outbuf, size_t outbuflen, const unsigned char *inbuf, size_t inbuflen); /*-- cipher-ctr.c --*/ gcry_err_code_t _gcry_cipher_ctr_encrypt /* */ (gcry_cipher_hd_t c, unsigned char *outbuf, size_t outbuflen, const unsigned char *inbuf, size_t inbuflen); /*-- cipher-aeswrap.c --*/ gcry_err_code_t _gcry_cipher_aeswrap_encrypt /* */ (gcry_cipher_hd_t c, byte *outbuf, size_t outbuflen, const byte *inbuf, size_t inbuflen); gcry_err_code_t _gcry_cipher_aeswrap_decrypt /* */ (gcry_cipher_hd_t c, byte *outbuf, size_t outbuflen, const byte *inbuf, size_t inbuflen); /*-- cipher-ccm.c --*/ gcry_err_code_t _gcry_cipher_ccm_encrypt /* */ (gcry_cipher_hd_t c, unsigned char *outbuf, size_t outbuflen, const unsigned char *inbuf, size_t inbuflen); gcry_err_code_t _gcry_cipher_ccm_decrypt /* */ (gcry_cipher_hd_t c, unsigned char *outbuf, size_t outbuflen, const unsigned char *inbuf, size_t inbuflen); gcry_err_code_t _gcry_cipher_ccm_set_nonce /* */ (gcry_cipher_hd_t c, const unsigned char *nonce, size_t noncelen); gcry_err_code_t _gcry_cipher_ccm_authenticate /* */ (gcry_cipher_hd_t c, const unsigned char *abuf, size_t abuflen); gcry_err_code_t _gcry_cipher_ccm_set_lengths /* */ (gcry_cipher_hd_t c, u64 encryptedlen, u64 aadlen, u64 taglen); gcry_err_code_t _gcry_cipher_ccm_get_tag /* */ (gcry_cipher_hd_t c, unsigned char *outtag, size_t taglen); gcry_err_code_t _gcry_cipher_ccm_check_tag /* */ (gcry_cipher_hd_t c, const unsigned char *intag, size_t taglen); /*-- cipher-gcm.c --*/ gcry_err_code_t _gcry_cipher_gcm_encrypt /* */ (gcry_cipher_hd_t c, unsigned char *outbuf, size_t outbuflen, const unsigned char *inbuf, size_t inbuflen); gcry_err_code_t _gcry_cipher_gcm_decrypt /* */ (gcry_cipher_hd_t c, unsigned char *outbuf, size_t outbuflen, const unsigned char *inbuf, size_t inbuflen); gcry_err_code_t _gcry_cipher_gcm_setiv /* */ (gcry_cipher_hd_t c, const unsigned char *iv, size_t ivlen); gcry_err_code_t _gcry_cipher_gcm_authenticate /* */ (gcry_cipher_hd_t c, const unsigned char *aadbuf, size_t aadbuflen); gcry_err_code_t _gcry_cipher_gcm_get_tag /* */ (gcry_cipher_hd_t c, unsigned char *outtag, size_t taglen); gcry_err_code_t _gcry_cipher_gcm_check_tag /* */ (gcry_cipher_hd_t c, const unsigned char *intag, size_t taglen); void _gcry_cipher_gcm_setkey /* */ (gcry_cipher_hd_t c); /*-- cipher-poly1305.c --*/ gcry_err_code_t _gcry_cipher_poly1305_encrypt /* */ (gcry_cipher_hd_t c, unsigned char *outbuf, size_t outbuflen, const unsigned char *inbuf, size_t inbuflen); gcry_err_code_t _gcry_cipher_poly1305_decrypt /* */ (gcry_cipher_hd_t c, unsigned char *outbuf, size_t outbuflen, const unsigned char *inbuf, size_t inbuflen); gcry_err_code_t _gcry_cipher_poly1305_setiv /* */ (gcry_cipher_hd_t c, const unsigned char *iv, size_t ivlen); gcry_err_code_t _gcry_cipher_poly1305_authenticate /* */ (gcry_cipher_hd_t c, const unsigned char *aadbuf, size_t aadbuflen); gcry_err_code_t _gcry_cipher_poly1305_get_tag /* */ (gcry_cipher_hd_t c, unsigned char *outtag, size_t taglen); gcry_err_code_t _gcry_cipher_poly1305_check_tag /* */ (gcry_cipher_hd_t c, const unsigned char *intag, size_t taglen); void _gcry_cipher_poly1305_setkey /* */ (gcry_cipher_hd_t c); /*-- cipher-ocb.c --*/ gcry_err_code_t _gcry_cipher_ocb_encrypt /* */ (gcry_cipher_hd_t c, unsigned char *outbuf, size_t outbuflen, const unsigned char *inbuf, size_t inbuflen); gcry_err_code_t _gcry_cipher_ocb_decrypt /* */ (gcry_cipher_hd_t c, unsigned char *outbuf, size_t outbuflen, const unsigned char *inbuf, size_t inbuflen); gcry_err_code_t _gcry_cipher_ocb_set_nonce /* */ (gcry_cipher_hd_t c, const unsigned char *nonce, size_t noncelen); gcry_err_code_t _gcry_cipher_ocb_authenticate /* */ (gcry_cipher_hd_t c, const unsigned char *abuf, size_t abuflen); gcry_err_code_t _gcry_cipher_ocb_get_tag /* */ (gcry_cipher_hd_t c, unsigned char *outtag, size_t taglen); gcry_err_code_t _gcry_cipher_ocb_check_tag /* */ (gcry_cipher_hd_t c, const unsigned char *intag, size_t taglen); /*-- cipher-xts.c --*/ gcry_err_code_t _gcry_cipher_xts_crypt /* */ (gcry_cipher_hd_t c, unsigned char *outbuf, size_t outbuflen, const unsigned char *inbuf, size_t inbuflen, int encrypt); /* Return the L-value for block N. Note: 'cipher_ocb.c' ensures that N * will never be multiple of 65536 (1 << OCB_L_TABLE_SIZE), thus N can * be directly passed to _gcry_ctz() function and resulting index will * never overflow the table. */ static inline const unsigned char * ocb_get_l (gcry_cipher_hd_t c, u64 n) { unsigned long ntz; #if ((defined(__i386__) || defined(__x86_64__)) && __GNUC__ >= 4) /* Assumes that N != 0. */ asm ("rep;bsfl %k[low], %k[ntz]\n\t" : [ntz] "=r" (ntz) : [low] "r" ((unsigned long)n) : "cc"); #else ntz = _gcry_ctz (n); #endif return c->u_mode.ocb.L[ntz]; } #endif /*G10_CIPHER_INTERNAL_H*/ diff --git a/cipher/cipher.c b/cipher/cipher.c index 124700e9..98127386 100644 --- a/cipher/cipher.c +++ b/cipher/cipher.c @@ -1,1680 +1,1680 @@ /* cipher.c - cipher dispatcher * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 * 2005, 2007, 2008, 2009, 2011 Free Software Foundation, Inc. * Copyright (C) 2013 g10 Code GmbH * * 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 . */ #include #include #include #include #include #include "g10lib.h" #include "../src/gcrypt-testapi.h" #include "cipher.h" #include "./cipher-internal.h" /* This is the list of the default ciphers, which are included in libgcrypt. */ static gcry_cipher_spec_t *cipher_list[] = { #if USE_BLOWFISH &_gcry_cipher_spec_blowfish, #endif #if USE_DES &_gcry_cipher_spec_des, &_gcry_cipher_spec_tripledes, #endif #if USE_ARCFOUR &_gcry_cipher_spec_arcfour, #endif #if USE_CAST5 &_gcry_cipher_spec_cast5, #endif #if USE_AES &_gcry_cipher_spec_aes, &_gcry_cipher_spec_aes192, &_gcry_cipher_spec_aes256, #endif #if USE_TWOFISH &_gcry_cipher_spec_twofish, &_gcry_cipher_spec_twofish128, #endif #if USE_SERPENT &_gcry_cipher_spec_serpent128, &_gcry_cipher_spec_serpent192, &_gcry_cipher_spec_serpent256, #endif #if USE_RFC2268 &_gcry_cipher_spec_rfc2268_40, &_gcry_cipher_spec_rfc2268_128, #endif #if USE_SEED &_gcry_cipher_spec_seed, #endif #if USE_CAMELLIA &_gcry_cipher_spec_camellia128, &_gcry_cipher_spec_camellia192, &_gcry_cipher_spec_camellia256, #endif #ifdef USE_IDEA &_gcry_cipher_spec_idea, #endif #if USE_SALSA20 &_gcry_cipher_spec_salsa20, &_gcry_cipher_spec_salsa20r12, #endif #if USE_GOST28147 &_gcry_cipher_spec_gost28147, #endif #if USE_CHACHA20 &_gcry_cipher_spec_chacha20, #endif NULL }; static int map_algo (int algo) { return algo; } /* Return the spec structure for the cipher algorithm ALGO. For an unknown algorithm NULL is returned. */ static gcry_cipher_spec_t * spec_from_algo (int algo) { int idx; gcry_cipher_spec_t *spec; algo = map_algo (algo); for (idx = 0; (spec = cipher_list[idx]); idx++) if (algo == spec->algo) return spec; return NULL; } /* Lookup a cipher's spec by its name. */ static gcry_cipher_spec_t * spec_from_name (const char *name) { gcry_cipher_spec_t *spec; int idx; const char **aliases; for (idx=0; (spec = cipher_list[idx]); idx++) { if (!stricmp (name, spec->name)) return spec; if (spec->aliases) { for (aliases = spec->aliases; *aliases; aliases++) if (!stricmp (name, *aliases)) return spec; } } return NULL; } /* Lookup a cipher's spec by its OID. */ static gcry_cipher_spec_t * spec_from_oid (const char *oid) { gcry_cipher_spec_t *spec; gcry_cipher_oid_spec_t *oid_specs; int idx, j; for (idx=0; (spec = cipher_list[idx]); idx++) { oid_specs = spec->oids; if (oid_specs) { for (j = 0; oid_specs[j].oid; j++) if (!stricmp (oid, oid_specs[j].oid)) return spec; } } return NULL; } /* Locate the OID in the oid table and return the spec or NULL if not found. An optional "oid." or "OID." prefix in OID is ignored, the OID is expected to be in standard IETF dotted notation. A pointer to the OID specification of the module implementing this algorithm is return in OID_SPEC unless passed as NULL.*/ static gcry_cipher_spec_t * search_oid (const char *oid, gcry_cipher_oid_spec_t *oid_spec) { gcry_cipher_spec_t *spec; int i; if (!oid) return NULL; if (!strncmp (oid, "oid.", 4) || !strncmp (oid, "OID.", 4)) oid += 4; spec = spec_from_oid (oid); if (spec && spec->oids) { for (i = 0; spec->oids[i].oid; i++) if (!stricmp (oid, spec->oids[i].oid)) { if (oid_spec) *oid_spec = spec->oids[i]; return spec; } } return NULL; } /* Map STRING to the cipher algorithm identifier. Returns the algorithm ID of the cipher for the given name or 0 if the name is not known. It is valid to pass NULL for STRING which results in a return value of 0. */ int _gcry_cipher_map_name (const char *string) { gcry_cipher_spec_t *spec; if (!string) return 0; /* If the string starts with a digit (optionally prefixed with either "OID." or "oid."), we first look into our table of ASN.1 object identifiers to figure out the algorithm */ spec = search_oid (string, NULL); if (spec) return spec->algo; spec = spec_from_name (string); if (spec) return spec->algo; return 0; } /* Given a STRING with an OID in dotted decimal notation, this function returns the cipher mode (GCRY_CIPHER_MODE_*) associated with that OID or 0 if no mode is known. Passing NULL for string yields a return value of 0. */ int _gcry_cipher_mode_from_oid (const char *string) { gcry_cipher_spec_t *spec; gcry_cipher_oid_spec_t oid_spec; if (!string) return 0; spec = search_oid (string, &oid_spec); if (spec) return oid_spec.mode; return 0; } /* Map the cipher algorithm identifier ALGORITHM to a string representing this algorithm. This string is the default name as used by Libgcrypt. A "?" is returned for an unknown algorithm. NULL is never returned. */ const char * _gcry_cipher_algo_name (int algorithm) { gcry_cipher_spec_t *spec; spec = spec_from_algo (algorithm); return spec? spec->name : "?"; } /* Flag the cipher algorithm with the identifier ALGORITHM as disabled. There is no error return, the function does nothing for unknown algorithms. Disabled algorithms are virtually not available in Libgcrypt. This is not thread safe and should thus be called early. */ static void disable_cipher_algo (int algo) { gcry_cipher_spec_t *spec = spec_from_algo (algo); if (spec) spec->flags.disabled = 1; } /* Return 0 if the cipher algorithm with identifier ALGORITHM is available. Returns a basic error code value if it is not available. */ static gcry_err_code_t check_cipher_algo (int algorithm) { gcry_cipher_spec_t *spec; spec = spec_from_algo (algorithm); if (spec && !spec->flags.disabled) return 0; return GPG_ERR_CIPHER_ALGO; } /* Return the standard length in bits of the key for the cipher algorithm with the identifier ALGORITHM. */ static unsigned int cipher_get_keylen (int algorithm) { gcry_cipher_spec_t *spec; unsigned len = 0; spec = spec_from_algo (algorithm); if (spec) { len = spec->keylen; if (!len) log_bug ("cipher %d w/o key length\n", algorithm); } return len; } /* Return the block length of the cipher algorithm with the identifier ALGORITHM. This function return 0 for an invalid algorithm. */ static unsigned int cipher_get_blocksize (int algorithm) { gcry_cipher_spec_t *spec; unsigned len = 0; spec = spec_from_algo (algorithm); if (spec) { len = spec->blocksize; if (!len) log_bug ("cipher %d w/o blocksize\n", algorithm); } return len; } /* Open a cipher handle for use with cipher algorithm ALGORITHM, using the cipher mode MODE (one of the GCRY_CIPHER_MODE_*) and return a handle in HANDLE. Put NULL into HANDLE and return an error code if something goes wrong. FLAGS may be used to modify the operation. The defined flags are: GCRY_CIPHER_SECURE: allocate all internal buffers in secure memory. GCRY_CIPHER_ENABLE_SYNC: Enable the sync operation as used in OpenPGP. GCRY_CIPHER_CBC_CTS: Enable CTS mode. GCRY_CIPHER_CBC_MAC: Enable MAC mode. Values for these flags may be combined using OR. */ gcry_err_code_t _gcry_cipher_open (gcry_cipher_hd_t *handle, int algo, int mode, unsigned int flags) { gcry_err_code_t rc; gcry_cipher_hd_t h = NULL; if (mode >= GCRY_CIPHER_MODE_INTERNAL) rc = GPG_ERR_INV_CIPHER_MODE; else rc = _gcry_cipher_open_internal (&h, algo, mode, flags); *handle = rc ? NULL : h; return rc; } gcry_err_code_t _gcry_cipher_open_internal (gcry_cipher_hd_t *handle, int algo, int mode, unsigned int flags) { int secure = (flags & GCRY_CIPHER_SECURE); gcry_cipher_spec_t *spec; gcry_cipher_hd_t h = NULL; gcry_err_code_t err; /* If the application missed to call the random poll function, we do it here to ensure that it is used once in a while. */ _gcry_fast_random_poll (); spec = spec_from_algo (algo); if (!spec) err = GPG_ERR_CIPHER_ALGO; else if (spec->flags.disabled) err = GPG_ERR_CIPHER_ALGO; else err = 0; /* check flags */ if ((! err) && ((flags & ~(0 | GCRY_CIPHER_SECURE | GCRY_CIPHER_ENABLE_SYNC | GCRY_CIPHER_CBC_CTS | GCRY_CIPHER_CBC_MAC)) || (flags & GCRY_CIPHER_CBC_CTS & GCRY_CIPHER_CBC_MAC))) err = GPG_ERR_CIPHER_ALGO; /* check that a valid mode has been requested */ if (! err) switch (mode) { case GCRY_CIPHER_MODE_CCM: if (spec->blocksize != GCRY_CCM_BLOCK_LEN) err = GPG_ERR_INV_CIPHER_MODE; if (!spec->encrypt || !spec->decrypt) err = GPG_ERR_INV_CIPHER_MODE; break; case GCRY_CIPHER_MODE_XTS: if (spec->blocksize != GCRY_XTS_BLOCK_LEN) err = GPG_ERR_INV_CIPHER_MODE; if (!spec->encrypt || !spec->decrypt) err = GPG_ERR_INV_CIPHER_MODE; break; case GCRY_CIPHER_MODE_ECB: case GCRY_CIPHER_MODE_CBC: case GCRY_CIPHER_MODE_CFB: case GCRY_CIPHER_MODE_CFB8: case GCRY_CIPHER_MODE_OFB: case GCRY_CIPHER_MODE_CTR: case GCRY_CIPHER_MODE_AESWRAP: case GCRY_CIPHER_MODE_CMAC: case GCRY_CIPHER_MODE_GCM: if (!spec->encrypt || !spec->decrypt) err = GPG_ERR_INV_CIPHER_MODE; break; case GCRY_CIPHER_MODE_POLY1305: if (!spec->stencrypt || !spec->stdecrypt || !spec->setiv) err = GPG_ERR_INV_CIPHER_MODE; else if (spec->algo != GCRY_CIPHER_CHACHA20) err = GPG_ERR_INV_CIPHER_MODE; break; case GCRY_CIPHER_MODE_OCB: /* Note that our implementation allows only for 128 bit block length algorithms. Lower block lengths would be possible but we do not implement them because they limit the security too much. */ if (!spec->encrypt || !spec->decrypt) err = GPG_ERR_INV_CIPHER_MODE; else if (spec->blocksize != (128/8)) err = GPG_ERR_INV_CIPHER_MODE; break; case GCRY_CIPHER_MODE_STREAM: if (!spec->stencrypt || !spec->stdecrypt) err = GPG_ERR_INV_CIPHER_MODE; break; case GCRY_CIPHER_MODE_NONE: /* This mode may be used for debugging. It copies the main text verbatim to the ciphertext. We do not allow this in fips mode or if no debug flag has been set. */ if (fips_mode () || !_gcry_get_debug_flag (0)) err = GPG_ERR_INV_CIPHER_MODE; break; default: err = GPG_ERR_INV_CIPHER_MODE; } /* Perform selftest here and mark this with a flag in cipher_table? No, we should not do this as it takes too long. Further it does not make sense to exclude algorithms with failing selftests at runtime: If a selftest fails there is something seriously wrong with the system and thus we better die immediately. */ if (! err) { size_t size = (sizeof (*h) + 2 * spec->contextsize - sizeof (cipher_context_alignment_t) #ifdef NEED_16BYTE_ALIGNED_CONTEXT + 15 /* Space for leading alignment gap. */ #endif /*NEED_16BYTE_ALIGNED_CONTEXT*/ ); /* Space needed per mode. */ switch (mode) { case GCRY_CIPHER_MODE_XTS: /* Additional cipher context for tweak. */ size += 2 * spec->contextsize + 15; break; default: break; } if (secure) h = xtrycalloc_secure (1, size); else h = xtrycalloc (1, size); if (! h) err = gpg_err_code_from_syserror (); else { size_t off = 0; char *tc; #ifdef NEED_16BYTE_ALIGNED_CONTEXT if ( ((uintptr_t)h & 0x0f) ) { /* The malloced block is not aligned on a 16 byte boundary. Correct for this. */ off = 16 - ((uintptr_t)h & 0x0f); h = (void*)((char*)h + off); } #endif /*NEED_16BYTE_ALIGNED_CONTEXT*/ h->magic = secure ? CTX_MAGIC_SECURE : CTX_MAGIC_NORMAL; h->actual_handle_size = size - off; h->handle_offset = off; h->spec = spec; h->algo = algo; h->mode = mode; h->flags = flags; /* Setup bulk encryption routines. */ switch (algo) { #ifdef USE_AES case GCRY_CIPHER_AES128: case GCRY_CIPHER_AES192: case GCRY_CIPHER_AES256: h->bulk.cfb_enc = _gcry_aes_cfb_enc; h->bulk.cfb_dec = _gcry_aes_cfb_dec; h->bulk.cbc_enc = _gcry_aes_cbc_enc; h->bulk.cbc_dec = _gcry_aes_cbc_dec; h->bulk.ctr_enc = _gcry_aes_ctr_enc; h->bulk.ocb_crypt = _gcry_aes_ocb_crypt; h->bulk.ocb_auth = _gcry_aes_ocb_auth; break; #endif /*USE_AES*/ #ifdef USE_BLOWFISH case GCRY_CIPHER_BLOWFISH: h->bulk.cfb_dec = _gcry_blowfish_cfb_dec; h->bulk.cbc_dec = _gcry_blowfish_cbc_dec; h->bulk.ctr_enc = _gcry_blowfish_ctr_enc; break; #endif /*USE_BLOWFISH*/ #ifdef USE_CAST5 case GCRY_CIPHER_CAST5: h->bulk.cfb_dec = _gcry_cast5_cfb_dec; h->bulk.cbc_dec = _gcry_cast5_cbc_dec; h->bulk.ctr_enc = _gcry_cast5_ctr_enc; break; #endif /*USE_CAMELLIA*/ #ifdef USE_CAMELLIA case GCRY_CIPHER_CAMELLIA128: case GCRY_CIPHER_CAMELLIA192: case GCRY_CIPHER_CAMELLIA256: h->bulk.cbc_dec = _gcry_camellia_cbc_dec; h->bulk.cfb_dec = _gcry_camellia_cfb_dec; h->bulk.ctr_enc = _gcry_camellia_ctr_enc; h->bulk.ocb_crypt = _gcry_camellia_ocb_crypt; h->bulk.ocb_auth = _gcry_camellia_ocb_auth; break; #endif /*USE_CAMELLIA*/ #ifdef USE_DES case GCRY_CIPHER_3DES: h->bulk.cbc_dec = _gcry_3des_cbc_dec; h->bulk.cfb_dec = _gcry_3des_cfb_dec; h->bulk.ctr_enc = _gcry_3des_ctr_enc; break; #endif /*USE_DES*/ #ifdef USE_SERPENT case GCRY_CIPHER_SERPENT128: case GCRY_CIPHER_SERPENT192: case GCRY_CIPHER_SERPENT256: h->bulk.cbc_dec = _gcry_serpent_cbc_dec; h->bulk.cfb_dec = _gcry_serpent_cfb_dec; h->bulk.ctr_enc = _gcry_serpent_ctr_enc; h->bulk.ocb_crypt = _gcry_serpent_ocb_crypt; h->bulk.ocb_auth = _gcry_serpent_ocb_auth; break; #endif /*USE_SERPENT*/ #ifdef USE_TWOFISH case GCRY_CIPHER_TWOFISH: case GCRY_CIPHER_TWOFISH128: h->bulk.cbc_dec = _gcry_twofish_cbc_dec; h->bulk.cfb_dec = _gcry_twofish_cfb_dec; h->bulk.ctr_enc = _gcry_twofish_ctr_enc; h->bulk.ocb_crypt = _gcry_twofish_ocb_crypt; h->bulk.ocb_auth = _gcry_twofish_ocb_auth; break; #endif /*USE_TWOFISH*/ default: break; } /* Setup defaults depending on the mode. */ switch (mode) { case GCRY_CIPHER_MODE_OCB: h->u_mode.ocb.taglen = 16; /* Bytes. */ break; case GCRY_CIPHER_MODE_XTS: tc = h->context.c + spec->contextsize * 2; tc += (16 - (uintptr_t)tc % 16) % 16; h->u_mode.xts.tweak_context = tc; break; default: break; } } } /* Done. */ *handle = err ? NULL : h; return err; } /* Release all resources associated with the cipher handle H. H may be NULL in which case this is a no-operation. */ void _gcry_cipher_close (gcry_cipher_hd_t h) { size_t off; if (!h) return; if ((h->magic != CTX_MAGIC_SECURE) && (h->magic != CTX_MAGIC_NORMAL)) _gcry_fatal_error(GPG_ERR_INTERNAL, "gcry_cipher_close: already closed/invalid handle"); else h->magic = 0; /* We always want to wipe out the memory even when the context has been allocated in secure memory. The user might have disabled secure memory or is using his own implementation which does not do the wiping. To accomplish this we need to keep track of the actual size of this structure because we have no way to known how large the allocated area was when using a standard malloc. */ off = h->handle_offset; wipememory (h, h->actual_handle_size); xfree ((char*)h - off); } /* Set the key to be used for the encryption context C to KEY with length KEYLEN. The length should match the required length. */ static gcry_err_code_t cipher_setkey (gcry_cipher_hd_t c, byte *key, size_t keylen) { gcry_err_code_t rc; if (c->mode == GCRY_CIPHER_MODE_XTS) { /* XTS uses two keys. */ if (keylen % 2) return GPG_ERR_INV_KEYLEN; keylen /= 2; if (fips_mode ()) { /* Reject key if subkeys Key_1 and Key_2 are equal. See "Implementation Guidance for FIPS 140-2, A.9 XTS-AES Key Generation Requirements" for details. */ if (buf_eq_const (key, key + keylen, keylen)) return GPG_ERR_WEAK_KEY; } } rc = c->spec->setkey (&c->context.c, key, keylen); if (!rc) { /* Duplicate initial context. */ memcpy ((void *) ((char *) &c->context.c + c->spec->contextsize), (void *) &c->context.c, c->spec->contextsize); c->marks.key = 1; switch (c->mode) { case GCRY_CIPHER_MODE_CMAC: _gcry_cipher_cmac_set_subkeys (c); break; case GCRY_CIPHER_MODE_GCM: _gcry_cipher_gcm_setkey (c); break; case GCRY_CIPHER_MODE_POLY1305: _gcry_cipher_poly1305_setkey (c); break; case GCRY_CIPHER_MODE_XTS: /* Setup tweak cipher with second part of XTS key. */ rc = c->spec->setkey (c->u_mode.xts.tweak_context, key + keylen, keylen); if (!rc) { /* Duplicate initial tweak context. */ memcpy (c->u_mode.xts.tweak_context + c->spec->contextsize, c->u_mode.xts.tweak_context, c->spec->contextsize); } else c->marks.key = 0; break; default: break; }; } else c->marks.key = 0; return rc; } /* Set the IV to be used for the encryption context C to IV with length IVLEN. The length should match the required length. */ static gcry_err_code_t cipher_setiv (gcry_cipher_hd_t c, const byte *iv, size_t ivlen) { /* If the cipher has its own IV handler, we use only this one. This is currently used for stream ciphers requiring a nonce. */ if (c->spec->setiv) { c->spec->setiv (&c->context.c, iv, ivlen); return 0; } memset (c->u_iv.iv, 0, c->spec->blocksize); if (iv) { if (ivlen != c->spec->blocksize) { log_info ("WARNING: cipher_setiv: ivlen=%u blklen=%u\n", (unsigned int)ivlen, (unsigned int)c->spec->blocksize); fips_signal_error ("IV length does not match blocklength"); } if (ivlen > c->spec->blocksize) ivlen = c->spec->blocksize; memcpy (c->u_iv.iv, iv, ivlen); c->marks.iv = 1; } else c->marks.iv = 0; c->unused = 0; return 0; } /* Reset the cipher context to the initial context. This is basically the same as an release followed by a new. */ static void cipher_reset (gcry_cipher_hd_t c) { unsigned int marks_key; marks_key = c->marks.key; memcpy (&c->context.c, (char *) &c->context.c + c->spec->contextsize, c->spec->contextsize); memset (&c->marks, 0, sizeof c->marks); memset (c->u_iv.iv, 0, c->spec->blocksize); memset (c->lastiv, 0, c->spec->blocksize); memset (c->u_ctr.ctr, 0, c->spec->blocksize); c->unused = 0; c->marks.key = marks_key; switch (c->mode) { case GCRY_CIPHER_MODE_CMAC: /* Only clear 'tag' for cmac, keep subkeys. */ c->u_mode.cmac.tag = 0; break; case GCRY_CIPHER_MODE_GCM: /* Only clear head of u_mode, keep ghash_key and gcm_table. */ { byte *u_mode_pos = (void *)&c->u_mode; byte *ghash_key_pos = c->u_mode.gcm.u_ghash_key.key; size_t u_mode_head_length = ghash_key_pos - u_mode_pos; memset (&c->u_mode, 0, u_mode_head_length); } break; case GCRY_CIPHER_MODE_POLY1305: memset (&c->u_mode.poly1305, 0, sizeof c->u_mode.poly1305); break; case GCRY_CIPHER_MODE_CCM: memset (&c->u_mode.ccm, 0, sizeof c->u_mode.ccm); break; case GCRY_CIPHER_MODE_OCB: memset (&c->u_mode.ocb, 0, sizeof c->u_mode.ocb); /* Setup default taglen. */ c->u_mode.ocb.taglen = 16; break; case GCRY_CIPHER_MODE_XTS: memcpy (c->u_mode.xts.tweak_context, c->u_mode.xts.tweak_context + c->spec->contextsize, c->spec->contextsize); break; default: break; /* u_mode unused by other modes. */ } } static gcry_err_code_t do_ecb_crypt (gcry_cipher_hd_t c, unsigned char *outbuf, size_t outbuflen, const unsigned char *inbuf, size_t inbuflen, gcry_cipher_encrypt_t crypt_fn) { unsigned int blocksize = c->spec->blocksize; size_t n, nblocks; unsigned int burn, nburn; if (outbuflen < inbuflen) return GPG_ERR_BUFFER_TOO_SHORT; if ((inbuflen % blocksize)) return GPG_ERR_INV_LENGTH; nblocks = inbuflen / blocksize; burn = 0; for (n=0; n < nblocks; n++ ) { nburn = crypt_fn (&c->context.c, outbuf, inbuf); burn = nburn > burn ? nburn : burn; inbuf += blocksize; outbuf += blocksize; } if (burn > 0) _gcry_burn_stack (burn + 4 * sizeof(void *)); return 0; } static gcry_err_code_t do_ecb_encrypt (gcry_cipher_hd_t c, unsigned char *outbuf, size_t outbuflen, const unsigned char *inbuf, size_t inbuflen) { return do_ecb_crypt (c, outbuf, outbuflen, inbuf, inbuflen, c->spec->encrypt); } static gcry_err_code_t do_ecb_decrypt (gcry_cipher_hd_t c, unsigned char *outbuf, size_t outbuflen, const unsigned char *inbuf, size_t inbuflen) { return do_ecb_crypt (c, outbuf, outbuflen, inbuf, inbuflen, c->spec->decrypt); } /**************** * Encrypt INBUF to OUTBUF with the mode selected at open. * inbuf and outbuf may overlap or be the same. * Depending on the mode some constraints apply to INBUFLEN. */ static gcry_err_code_t cipher_encrypt (gcry_cipher_hd_t c, byte *outbuf, size_t outbuflen, const byte *inbuf, size_t inbuflen) { gcry_err_code_t rc; if (c->mode != GCRY_CIPHER_MODE_NONE && !c->marks.key) { log_error ("cipher_encrypt: key not set\n"); return GPG_ERR_MISSING_KEY; } switch (c->mode) { case GCRY_CIPHER_MODE_ECB: rc = do_ecb_encrypt (c, outbuf, outbuflen, inbuf, inbuflen); break; case GCRY_CIPHER_MODE_CBC: rc = _gcry_cipher_cbc_encrypt (c, outbuf, outbuflen, inbuf, inbuflen); break; case GCRY_CIPHER_MODE_CFB: rc = _gcry_cipher_cfb_encrypt (c, outbuf, outbuflen, inbuf, inbuflen); break; case GCRY_CIPHER_MODE_CFB8: rc = _gcry_cipher_cfb8_encrypt (c, outbuf, outbuflen, inbuf, inbuflen); break; case GCRY_CIPHER_MODE_OFB: rc = _gcry_cipher_ofb_encrypt (c, outbuf, outbuflen, inbuf, inbuflen); break; case GCRY_CIPHER_MODE_CTR: rc = _gcry_cipher_ctr_encrypt (c, outbuf, outbuflen, inbuf, inbuflen); break; case GCRY_CIPHER_MODE_AESWRAP: rc = _gcry_cipher_aeswrap_encrypt (c, outbuf, outbuflen, inbuf, inbuflen); break; case GCRY_CIPHER_MODE_CCM: rc = _gcry_cipher_ccm_encrypt (c, outbuf, outbuflen, inbuf, inbuflen); break; case GCRY_CIPHER_MODE_CMAC: rc = GPG_ERR_INV_CIPHER_MODE; break; case GCRY_CIPHER_MODE_GCM: rc = _gcry_cipher_gcm_encrypt (c, outbuf, outbuflen, inbuf, inbuflen); break; case GCRY_CIPHER_MODE_POLY1305: rc = _gcry_cipher_poly1305_encrypt (c, outbuf, outbuflen, inbuf, inbuflen); break; case GCRY_CIPHER_MODE_OCB: rc = _gcry_cipher_ocb_encrypt (c, outbuf, outbuflen, inbuf, inbuflen); break; case GCRY_CIPHER_MODE_XTS: rc = _gcry_cipher_xts_crypt (c, outbuf, outbuflen, inbuf, inbuflen, 1); break; case GCRY_CIPHER_MODE_STREAM: c->spec->stencrypt (&c->context.c, outbuf, (byte*)/*arggg*/inbuf, inbuflen); rc = 0; break; case GCRY_CIPHER_MODE_NONE: if (fips_mode () || !_gcry_get_debug_flag (0)) { fips_signal_error ("cipher mode NONE used"); rc = GPG_ERR_INV_CIPHER_MODE; } else { if (inbuf != outbuf) memmove (outbuf, inbuf, inbuflen); rc = 0; } break; default: log_fatal ("cipher_encrypt: invalid mode %d\n", c->mode ); rc = GPG_ERR_INV_CIPHER_MODE; break; } return rc; } /**************** * Encrypt IN and write it to OUT. If IN is NULL, in-place encryption has * been requested. */ gcry_err_code_t _gcry_cipher_encrypt (gcry_cipher_hd_t h, void *out, size_t outsize, const void *in, size_t inlen) { gcry_err_code_t rc; if (!in) /* Caller requested in-place encryption. */ { in = out; inlen = outsize; } rc = cipher_encrypt (h, out, outsize, in, inlen); /* Failsafe: Make sure that the plaintext will never make it into OUT if the encryption returned an error. */ if (rc && out) memset (out, 0x42, outsize); return rc; } /**************** * Decrypt INBUF to OUTBUF with the mode selected at open. * inbuf and outbuf may overlap or be the same. - * Depending on the mode some some contraints apply to INBUFLEN. + * Depending on the mode some some constraints apply to INBUFLEN. */ static gcry_err_code_t cipher_decrypt (gcry_cipher_hd_t c, byte *outbuf, size_t outbuflen, const byte *inbuf, size_t inbuflen) { gcry_err_code_t rc; if (c->mode != GCRY_CIPHER_MODE_NONE && !c->marks.key) { log_error ("cipher_decrypt: key not set\n"); return GPG_ERR_MISSING_KEY; } switch (c->mode) { case GCRY_CIPHER_MODE_ECB: rc = do_ecb_decrypt (c, outbuf, outbuflen, inbuf, inbuflen); break; case GCRY_CIPHER_MODE_CBC: rc = _gcry_cipher_cbc_decrypt (c, outbuf, outbuflen, inbuf, inbuflen); break; case GCRY_CIPHER_MODE_CFB: rc = _gcry_cipher_cfb_decrypt (c, outbuf, outbuflen, inbuf, inbuflen); break; case GCRY_CIPHER_MODE_CFB8: rc = _gcry_cipher_cfb8_decrypt (c, outbuf, outbuflen, inbuf, inbuflen); break; case GCRY_CIPHER_MODE_OFB: rc = _gcry_cipher_ofb_encrypt (c, outbuf, outbuflen, inbuf, inbuflen); break; case GCRY_CIPHER_MODE_CTR: rc = _gcry_cipher_ctr_encrypt (c, outbuf, outbuflen, inbuf, inbuflen); break; case GCRY_CIPHER_MODE_AESWRAP: rc = _gcry_cipher_aeswrap_decrypt (c, outbuf, outbuflen, inbuf, inbuflen); break; case GCRY_CIPHER_MODE_CCM: rc = _gcry_cipher_ccm_decrypt (c, outbuf, outbuflen, inbuf, inbuflen); break; case GCRY_CIPHER_MODE_CMAC: rc = GPG_ERR_INV_CIPHER_MODE; break; case GCRY_CIPHER_MODE_GCM: rc = _gcry_cipher_gcm_decrypt (c, outbuf, outbuflen, inbuf, inbuflen); break; case GCRY_CIPHER_MODE_POLY1305: rc = _gcry_cipher_poly1305_decrypt (c, outbuf, outbuflen, inbuf, inbuflen); break; case GCRY_CIPHER_MODE_OCB: rc = _gcry_cipher_ocb_decrypt (c, outbuf, outbuflen, inbuf, inbuflen); break; case GCRY_CIPHER_MODE_XTS: rc = _gcry_cipher_xts_crypt (c, outbuf, outbuflen, inbuf, inbuflen, 0); break; case GCRY_CIPHER_MODE_STREAM: c->spec->stdecrypt (&c->context.c, outbuf, (byte*)/*arggg*/inbuf, inbuflen); rc = 0; break; case GCRY_CIPHER_MODE_NONE: if (fips_mode () || !_gcry_get_debug_flag (0)) { fips_signal_error ("cipher mode NONE used"); rc = GPG_ERR_INV_CIPHER_MODE; } else { if (inbuf != outbuf) memmove (outbuf, inbuf, inbuflen); rc = 0; } break; default: log_fatal ("cipher_decrypt: invalid mode %d\n", c->mode ); rc = GPG_ERR_INV_CIPHER_MODE; break; } return rc; } gcry_err_code_t _gcry_cipher_decrypt (gcry_cipher_hd_t h, void *out, size_t outsize, const void *in, size_t inlen) { if (!in) /* Caller requested in-place encryption. */ { in = out; inlen = outsize; } return cipher_decrypt (h, out, outsize, in, inlen); } /**************** * Used for PGP's somewhat strange CFB mode. Only works if * the corresponding flag is set. */ static void cipher_sync (gcry_cipher_hd_t c) { if ((c->flags & GCRY_CIPHER_ENABLE_SYNC) && c->unused) { memmove (c->u_iv.iv + c->unused, c->u_iv.iv, c->spec->blocksize - c->unused); memcpy (c->u_iv.iv, c->lastiv + c->spec->blocksize - c->unused, c->unused); c->unused = 0; } } gcry_err_code_t _gcry_cipher_setkey (gcry_cipher_hd_t hd, const void *key, size_t keylen) { return cipher_setkey (hd, (void*)key, keylen); } gcry_err_code_t _gcry_cipher_setiv (gcry_cipher_hd_t hd, const void *iv, size_t ivlen) { gcry_err_code_t rc = 0; switch (hd->mode) { case GCRY_CIPHER_MODE_CCM: rc = _gcry_cipher_ccm_set_nonce (hd, iv, ivlen); break; case GCRY_CIPHER_MODE_GCM: rc = _gcry_cipher_gcm_setiv (hd, iv, ivlen); break; case GCRY_CIPHER_MODE_POLY1305: rc = _gcry_cipher_poly1305_setiv (hd, iv, ivlen); break; case GCRY_CIPHER_MODE_OCB: rc = _gcry_cipher_ocb_set_nonce (hd, iv, ivlen); break; default: rc = cipher_setiv (hd, iv, ivlen); break; } return rc; } /* 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_err_code_t _gcry_cipher_setctr (gcry_cipher_hd_t hd, const void *ctr, size_t ctrlen) { if (ctr && ctrlen == hd->spec->blocksize) { memcpy (hd->u_ctr.ctr, ctr, hd->spec->blocksize); hd->unused = 0; } else if (!ctr || !ctrlen) { memset (hd->u_ctr.ctr, 0, hd->spec->blocksize); hd->unused = 0; } else return GPG_ERR_INV_ARG; return 0; } gpg_err_code_t _gcry_cipher_getctr (gcry_cipher_hd_t hd, void *ctr, size_t ctrlen) { if (ctr && ctrlen == hd->spec->blocksize) memcpy (ctr, hd->u_ctr.ctr, hd->spec->blocksize); else return GPG_ERR_INV_ARG; return 0; } gcry_err_code_t _gcry_cipher_authenticate (gcry_cipher_hd_t hd, const void *abuf, size_t abuflen) { gcry_err_code_t rc; switch (hd->mode) { case GCRY_CIPHER_MODE_CCM: rc = _gcry_cipher_ccm_authenticate (hd, abuf, abuflen); break; case GCRY_CIPHER_MODE_CMAC: rc = _gcry_cipher_cmac_authenticate (hd, abuf, abuflen); break; case GCRY_CIPHER_MODE_GCM: rc = _gcry_cipher_gcm_authenticate (hd, abuf, abuflen); break; case GCRY_CIPHER_MODE_POLY1305: rc = _gcry_cipher_poly1305_authenticate (hd, abuf, abuflen); break; case GCRY_CIPHER_MODE_OCB: rc = _gcry_cipher_ocb_authenticate (hd, abuf, abuflen); break; default: log_error ("gcry_cipher_authenticate: invalid mode %d\n", hd->mode); rc = GPG_ERR_INV_CIPHER_MODE; break; } return rc; } gcry_err_code_t _gcry_cipher_gettag (gcry_cipher_hd_t hd, void *outtag, size_t taglen) { gcry_err_code_t rc; switch (hd->mode) { case GCRY_CIPHER_MODE_CCM: rc = _gcry_cipher_ccm_get_tag (hd, outtag, taglen); break; case GCRY_CIPHER_MODE_CMAC: rc = _gcry_cipher_cmac_get_tag (hd, outtag, taglen); break; case GCRY_CIPHER_MODE_GCM: rc = _gcry_cipher_gcm_get_tag (hd, outtag, taglen); break; case GCRY_CIPHER_MODE_POLY1305: rc = _gcry_cipher_poly1305_get_tag (hd, outtag, taglen); break; case GCRY_CIPHER_MODE_OCB: rc = _gcry_cipher_ocb_get_tag (hd, outtag, taglen); break; default: log_error ("gcry_cipher_gettag: invalid mode %d\n", hd->mode); rc = GPG_ERR_INV_CIPHER_MODE; break; } return rc; } gcry_err_code_t _gcry_cipher_checktag (gcry_cipher_hd_t hd, const void *intag, size_t taglen) { gcry_err_code_t rc; switch (hd->mode) { case GCRY_CIPHER_MODE_CCM: rc = _gcry_cipher_ccm_check_tag (hd, intag, taglen); break; case GCRY_CIPHER_MODE_CMAC: rc = _gcry_cipher_cmac_check_tag (hd, intag, taglen); break; case GCRY_CIPHER_MODE_GCM: rc = _gcry_cipher_gcm_check_tag (hd, intag, taglen); break; case GCRY_CIPHER_MODE_POLY1305: rc = _gcry_cipher_poly1305_check_tag (hd, intag, taglen); break; case GCRY_CIPHER_MODE_OCB: rc = _gcry_cipher_ocb_check_tag (hd, intag, taglen); break; default: log_error ("gcry_cipher_checktag: invalid mode %d\n", hd->mode); rc = GPG_ERR_INV_CIPHER_MODE; break; } return rc; } gcry_err_code_t _gcry_cipher_ctl (gcry_cipher_hd_t h, int cmd, void *buffer, size_t buflen) { gcry_err_code_t rc = 0; switch (cmd) { case GCRYCTL_RESET: cipher_reset (h); break; case GCRYCTL_FINALIZE: if (!h || buffer || buflen) return GPG_ERR_INV_ARG; h->marks.finalize = 1; break; case GCRYCTL_CFB_SYNC: cipher_sync( h ); break; case GCRYCTL_SET_CBC_CTS: if (buflen) if (h->flags & GCRY_CIPHER_CBC_MAC) rc = GPG_ERR_INV_FLAG; else h->flags |= GCRY_CIPHER_CBC_CTS; else h->flags &= ~GCRY_CIPHER_CBC_CTS; break; case GCRYCTL_SET_CBC_MAC: if (buflen) if (h->flags & GCRY_CIPHER_CBC_CTS) rc = GPG_ERR_INV_FLAG; else h->flags |= GCRY_CIPHER_CBC_MAC; else h->flags &= ~GCRY_CIPHER_CBC_MAC; break; case GCRYCTL_SET_CCM_LENGTHS: { u64 params[3]; size_t encryptedlen; size_t aadlen; size_t authtaglen; if (h->mode != GCRY_CIPHER_MODE_CCM) return GPG_ERR_INV_CIPHER_MODE; if (!buffer || buflen != 3 * sizeof(u64)) return GPG_ERR_INV_ARG; /* This command is used to pass additional length parameters needed by CCM mode to initialize CBC-MAC. */ memcpy (params, buffer, sizeof(params)); encryptedlen = params[0]; aadlen = params[1]; authtaglen = params[2]; rc = _gcry_cipher_ccm_set_lengths (h, encryptedlen, aadlen, authtaglen); } break; case GCRYCTL_SET_TAGLEN: if (!h || !buffer || buflen != sizeof(int) ) return GPG_ERR_INV_ARG; switch (h->mode) { case GCRY_CIPHER_MODE_OCB: switch (*(int*)buffer) { case 8: case 12: case 16: h->u_mode.ocb.taglen = *(int*)buffer; break; default: rc = GPG_ERR_INV_LENGTH; /* Invalid tag length. */ break; } break; default: rc =GPG_ERR_INV_CIPHER_MODE; break; } break; case GCRYCTL_DISABLE_ALGO: /* This command expects NULL for H and BUFFER to point to an integer with the algo number. */ if( h || !buffer || buflen != sizeof(int) ) return GPG_ERR_CIPHER_ALGO; disable_cipher_algo( *(int*)buffer ); break; case PRIV_CIPHERCTL_DISABLE_WEAK_KEY: /* (private) */ if (h->spec->set_extra_info) rc = h->spec->set_extra_info (&h->context.c, CIPHER_INFO_NO_WEAK_KEY, NULL, 0); else rc = GPG_ERR_NOT_SUPPORTED; break; case PRIV_CIPHERCTL_GET_INPUT_VECTOR: /* (private) */ /* This is the input block as used in CFB and OFB mode which has initially been set as IV. The returned format is: 1 byte Actual length of the block in bytes. n byte The block. If the provided buffer is too short, an error is returned. */ if (buflen < (1 + h->spec->blocksize)) rc = GPG_ERR_TOO_SHORT; else { unsigned char *ivp; unsigned char *dst = buffer; int n = h->unused; if (!n) n = h->spec->blocksize; gcry_assert (n <= h->spec->blocksize); *dst++ = n; ivp = h->u_iv.iv + h->spec->blocksize - n; while (n--) *dst++ = *ivp++; } break; case GCRYCTL_SET_SBOX: if (h->spec->set_extra_info) rc = h->spec->set_extra_info (&h->context.c, GCRYCTL_SET_SBOX, buffer, buflen); else rc = GPG_ERR_NOT_SUPPORTED; break; default: rc = GPG_ERR_INV_OP; } return rc; } /* Return information about the cipher handle H. CMD is the kind of * information requested. * * CMD may be one of: * * GCRYCTL_GET_TAGLEN: * Return the length of the tag for an AE algorithm mode. An * error is returned for modes which do not support a tag. * BUFFER must be given as NULL. On success the result is stored * at NBYTES. The taglen is returned in bytes. * * The function returns 0 on success or an error code. */ gcry_err_code_t _gcry_cipher_info (gcry_cipher_hd_t h, int cmd, void *buffer, size_t *nbytes) { gcry_err_code_t rc = 0; switch (cmd) { case GCRYCTL_GET_TAGLEN: if (!h || buffer || !nbytes) rc = GPG_ERR_INV_ARG; else { switch (h->mode) { case GCRY_CIPHER_MODE_OCB: *nbytes = h->u_mode.ocb.taglen; break; case GCRY_CIPHER_MODE_CCM: *nbytes = h->u_mode.ccm.authlen; break; case GCRY_CIPHER_MODE_GCM: *nbytes = GCRY_GCM_BLOCK_LEN; break; case GCRY_CIPHER_MODE_POLY1305: *nbytes = POLY1305_TAGLEN; break; default: rc = GPG_ERR_INV_CIPHER_MODE; break; } } break; default: rc = GPG_ERR_INV_OP; } return rc; } /* Return information about the given cipher algorithm ALGO. WHAT select the kind of information returned: GCRYCTL_GET_KEYLEN: Return the length of the key. If the algorithm ALGO supports multiple key lengths, the maximum supported key length is returned. The key length is returned as number of octets. BUFFER and NBYTES must be zero. GCRYCTL_GET_BLKLEN: Return the blocklength of the algorithm ALGO counted in octets. BUFFER and NBYTES must be zero. GCRYCTL_TEST_ALGO: Returns 0 if the specified algorithm ALGO is available for use. BUFFER and NBYTES must be zero. Note: Because this function is in most cases used to return an integer value, we can make it easier for the caller to just look at the return value. The caller will in all cases consult the value and thereby detecting whether a error occurred or not (i.e. while checking the block size) */ gcry_err_code_t _gcry_cipher_algo_info (int algo, int what, void *buffer, size_t *nbytes) { gcry_err_code_t rc = 0; unsigned int ui; switch (what) { case GCRYCTL_GET_KEYLEN: if (buffer || (! nbytes)) rc = GPG_ERR_CIPHER_ALGO; else { ui = cipher_get_keylen (algo); if ((ui > 0) && (ui <= 512)) *nbytes = (size_t) ui / 8; else /* The only reason for an error is an invalid algo. */ rc = GPG_ERR_CIPHER_ALGO; } break; case GCRYCTL_GET_BLKLEN: if (buffer || (! nbytes)) rc = GPG_ERR_CIPHER_ALGO; else { ui = cipher_get_blocksize (algo); if ((ui > 0) && (ui < 10000)) *nbytes = ui; else { /* The only reason is an invalid algo or a strange blocksize. */ rc = GPG_ERR_CIPHER_ALGO; } } break; case GCRYCTL_TEST_ALGO: if (buffer || nbytes) rc = GPG_ERR_INV_ARG; else rc = check_cipher_algo (algo); break; default: rc = GPG_ERR_INV_OP; } return rc; } /* This function returns length of the key for algorithm ALGO. If the algorithm supports multiple key lengths, the maximum supported key length is returned. On error 0 is returned. The key length is returned as number of octets. This is a convenience functions which should be preferred over gcry_cipher_algo_info because it allows for proper type checking. */ size_t _gcry_cipher_get_algo_keylen (int algo) { size_t n; if (_gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL, &n)) n = 0; return n; } /* This functions returns the blocklength of the algorithm ALGO counted in octets. On error 0 is returned. This is a convenience functions which should be preferred over gcry_cipher_algo_info because it allows for proper type checking. */ size_t _gcry_cipher_get_algo_blklen (int algo) { size_t n; if (_gcry_cipher_algo_info( algo, GCRYCTL_GET_BLKLEN, NULL, &n)) n = 0; return n; } /* Explicitly initialize this module. */ gcry_err_code_t _gcry_cipher_init (void) { if (fips_mode()) { /* disable algorithms that are disallowed in fips */ int idx; gcry_cipher_spec_t *spec; for (idx = 0; (spec = cipher_list[idx]); idx++) if (!spec->flags.fips) spec->flags.disabled = 1; } return 0; } /* Run the selftests for cipher algorithm ALGO with optional reporting function REPORT. */ gpg_error_t _gcry_cipher_selftest (int algo, int extended, selftest_report_func_t report) { gcry_err_code_t ec = 0; gcry_cipher_spec_t *spec; spec = spec_from_algo (algo); if (spec && !spec->flags.disabled && spec->selftest) ec = spec->selftest (algo, extended, report); else { ec = GPG_ERR_CIPHER_ALGO; if (report) report ("cipher", algo, "module", (spec && !spec->flags.disabled)? "no selftest available" : spec? "algorithm disabled" : "algorithm not found"); } return gpg_error (ec); } diff --git a/cipher/ecc-misc.c b/cipher/ecc-misc.c index 8f7b8c4d..41debe40 100644 --- a/cipher/ecc-misc.c +++ b/cipher/ecc-misc.c @@ -1,369 +1,369 @@ /* ecc-misc.c - Elliptic Curve miscellaneous functions * Copyright (C) 2007, 2008, 2010, 2011 Free Software Foundation, Inc. * Copyright (C) 2013 g10 Code GmbH * * 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 . */ #include #include #include #include #include #include "g10lib.h" #include "mpi.h" #include "cipher.h" #include "context.h" #include "ec-context.h" #include "ecc-common.h" /* * Release a curve object. */ void _gcry_ecc_curve_free (elliptic_curve_t *E) { mpi_free (E->p); E->p = NULL; mpi_free (E->a); E->a = NULL; mpi_free (E->b); E->b = NULL; _gcry_mpi_point_free_parts (&E->G); mpi_free (E->n); E->n = NULL; mpi_free (E->h); E->h = NULL; } /* * Return a copy of a curve object. */ elliptic_curve_t _gcry_ecc_curve_copy (elliptic_curve_t E) { elliptic_curve_t R; R.model = E.model; R.dialect = E.dialect; R.name = E.name; R.p = mpi_copy (E.p); R.a = mpi_copy (E.a); R.b = mpi_copy (E.b); _gcry_mpi_point_init (&R.G); point_set (&R.G, &E.G); R.n = mpi_copy (E.n); R.h = mpi_copy (E.h); return R; } /* * Return a description of the curve model. */ const char * _gcry_ecc_model2str (enum gcry_mpi_ec_models model) { const char *str = "?"; switch (model) { case MPI_EC_WEIERSTRASS: str = "Weierstrass"; break; case MPI_EC_MONTGOMERY: str = "Montgomery"; break; case MPI_EC_EDWARDS: str = "Edwards"; break; } return str; } /* * Return a description of the curve dialect. */ const char * _gcry_ecc_dialect2str (enum ecc_dialects dialect) { const char *str = "?"; switch (dialect) { case ECC_DIALECT_STANDARD: str = "Standard"; break; case ECC_DIALECT_ED25519: str = "Ed25519"; break; } return str; } gcry_mpi_t _gcry_ecc_ec2os (gcry_mpi_t x, gcry_mpi_t y, gcry_mpi_t p) { gpg_err_code_t rc; int pbytes = (mpi_get_nbits (p)+7)/8; size_t n; unsigned char *buf, *ptr; gcry_mpi_t result; buf = xmalloc ( 1 + 2*pbytes ); *buf = 04; /* Uncompressed point. */ ptr = buf+1; rc = _gcry_mpi_print (GCRYMPI_FMT_USG, ptr, pbytes, &n, x); if (rc) log_fatal ("mpi_print failed: %s\n", gpg_strerror (rc)); if (n < pbytes) { memmove (ptr+(pbytes-n), ptr, n); memset (ptr, 0, (pbytes-n)); } ptr += pbytes; rc = _gcry_mpi_print (GCRYMPI_FMT_USG, ptr, pbytes, &n, y); if (rc) log_fatal ("mpi_print failed: %s\n", gpg_strerror (rc)); if (n < pbytes) { memmove (ptr+(pbytes-n), ptr, n); memset (ptr, 0, (pbytes-n)); } rc = _gcry_mpi_scan (&result, GCRYMPI_FMT_USG, buf, 1+2*pbytes, NULL); if (rc) log_fatal ("mpi_scan failed: %s\n", gpg_strerror (rc)); xfree (buf); return result; } /* Convert POINT into affine coordinates using the context CTX and return a newly allocated MPI. If the conversion is not possible NULL is returned. This function won't print an error message. */ gcry_mpi_t _gcry_mpi_ec_ec2os (gcry_mpi_point_t point, mpi_ec_t ectx) { gcry_mpi_t g_x, g_y, result; g_x = mpi_new (0); g_y = mpi_new (0); if (_gcry_mpi_ec_get_affine (g_x, g_y, point, ectx)) result = NULL; else result = _gcry_ecc_ec2os (g_x, g_y, ectx->p); mpi_free (g_x); mpi_free (g_y); return result; } /* RESULT must have been initialized and is set on success to the point given by VALUE. */ gcry_err_code_t _gcry_ecc_os2ec (mpi_point_t result, gcry_mpi_t value) { gcry_err_code_t rc; size_t n; const unsigned char *buf; unsigned char *buf_memory; gcry_mpi_t x, y; if (mpi_is_opaque (value)) { unsigned int nbits; buf = mpi_get_opaque (value, &nbits); if (!buf) return GPG_ERR_INV_OBJ; n = (nbits + 7)/8; buf_memory = NULL; } else { n = (mpi_get_nbits (value)+7)/8; buf_memory = xmalloc (n); rc = _gcry_mpi_print (GCRYMPI_FMT_USG, buf_memory, n, &n, value); if (rc) { xfree (buf_memory); return rc; } buf = buf_memory; } if (n < 1) { xfree (buf_memory); return GPG_ERR_INV_OBJ; } if (*buf != 4) { xfree (buf_memory); return GPG_ERR_NOT_IMPLEMENTED; /* No support for point compression. */ } if ( ((n-1)%2) ) { xfree (buf_memory); return GPG_ERR_INV_OBJ; } n = (n-1)/2; rc = _gcry_mpi_scan (&x, GCRYMPI_FMT_USG, buf+1, n, NULL); if (rc) { xfree (buf_memory); return rc; } rc = _gcry_mpi_scan (&y, GCRYMPI_FMT_USG, buf+1+n, n, NULL); xfree (buf_memory); if (rc) { mpi_free (x); return rc; } mpi_set (result->x, x); mpi_set (result->y, y); mpi_set_ui (result->z, 1); mpi_free (x); mpi_free (y); return 0; } /* Compute the public key from the the context EC. Obviously a requirement is that the secret key is available in EC. On success Q is returned; on error NULL. If Q is NULL a newly allocated point is returned. If G or D are given they override the values taken from EC. */ mpi_point_t _gcry_ecc_compute_public (mpi_point_t Q, mpi_ec_t ec, mpi_point_t G, gcry_mpi_t d) { if (!G) G = ec->G; if (!d) d = ec->d; if (!d || !G || !ec->p || !ec->a) return NULL; if (ec->model == MPI_EC_EDWARDS && !ec->b) return NULL; if (ec->dialect == ECC_DIALECT_ED25519 && (ec->flags & PUBKEY_FLAG_EDDSA)) { gcry_mpi_t a; unsigned char *digest; if (_gcry_ecc_eddsa_compute_h_d (&digest, d, ec)) return NULL; a = mpi_snew (0); _gcry_mpi_set_buffer (a, digest, 32, 0); xfree (digest); /* And finally the public key. */ if (!Q) Q = mpi_point_new (0); if (Q) _gcry_mpi_ec_mul_point (Q, a, G, ec); mpi_free (a); } else { if (!Q) Q = mpi_point_new (0); if (Q) _gcry_mpi_ec_mul_point (Q, d, G, ec); } return Q; } gpg_err_code_t _gcry_ecc_mont_decodepoint (gcry_mpi_t pk, mpi_ec_t ctx, mpi_point_t result) { unsigned char *rawmpi; unsigned int rawmpilen; if (mpi_is_opaque (pk)) { const unsigned char *buf; unsigned char *p; buf = mpi_get_opaque (pk, &rawmpilen); if (!buf) return GPG_ERR_INV_OBJ; rawmpilen = (rawmpilen + 7)/8; if (rawmpilen > 1 && (rawmpilen%2) && buf[0] == 0x40) { rawmpilen--; buf++; } rawmpi = xtrymalloc (rawmpilen? rawmpilen:1); if (!rawmpi) return gpg_err_code_from_syserror (); p = rawmpi + rawmpilen; while (p > rawmpi) *--p = *buf++; } else { unsigned int nbytes = (ctx->nbits+7)/8; rawmpi = _gcry_mpi_get_buffer (pk, nbytes, &rawmpilen, NULL); if (!rawmpi) return gpg_err_code_from_syserror (); /* * It is not reliable to assume that 0x40 means the prefix. * * For newer implementation, it is reliable since we always put * 0x40 for x-only coordinate. * * For data with older implementation (non-released development - * version), it is possibe to have the 0x40 as a part of data. + * version), it is possible to have the 0x40 as a part of data. * Besides, when data was parsed as MPI, we might have 0x00 * prefix. * * So, we need to check if it's really the prefix or not. * Only when it's the prefix, we remove it. */ if (pk->nlimbs * BYTES_PER_MPI_LIMB < nbytes) {/* * It is possible for data created by older implementation * to have shorter length when it was parsed as MPI. */ unsigned int len = pk->nlimbs * BYTES_PER_MPI_LIMB; memmove (rawmpi + nbytes - len, rawmpi, len); memset (rawmpi, 0, nbytes - len); } /* * When we have the prefix (0x40 or 0x00), it comes at the end, * since it is taken by _gcry_mpi_get_buffer with little endian. * Just setting RAWMPILEN to NBYTES is enough in this case. * Othewise, RAWMPILEN is NBYTES already. */ rawmpilen = nbytes; } rawmpi[0] &= (1 << (ctx->nbits % 8)) - 1; _gcry_mpi_set_buffer (result->x, rawmpi, rawmpilen, 0); xfree (rawmpi); mpi_set_ui (result->z, 1); return 0; } diff --git a/cipher/primegen.c b/cipher/primegen.c index cccda84e..c7977d10 100644 --- a/cipher/primegen.c +++ b/cipher/primegen.c @@ -1,1872 +1,1872 @@ /* primegen.c - prime number generator * Copyright (C) 1998, 2000, 2001, 2002, 2003 * 2004, 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, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ #include #include #include #include #include #include "g10lib.h" #include "mpi.h" #include "cipher.h" static gcry_mpi_t gen_prime (unsigned int nbits, int secret, int randomlevel, int (*extra_check)(void *, gcry_mpi_t), void *extra_check_arg); static int check_prime( gcry_mpi_t prime, gcry_mpi_t val_2, int rm_rounds, gcry_prime_check_func_t cb_func, void *cb_arg ); static int is_prime (gcry_mpi_t n, int steps, unsigned int *count); static void m_out_of_n( char *array, int m, int n ); static void (*progress_cb) (void *,const char*,int,int, int ); static void *progress_cb_data; /* Note: 2 is not included because it can be tested more easily by looking at bit 0. The last entry in this list is marked by a zero */ static ushort small_prime_numbers[] = { 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551, 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999, 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137, 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209, 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271, 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331, 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467, 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533, 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583, 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643, 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779, 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851, 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917, 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989, 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111, 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177, 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243, 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297, 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457, 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519, 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597, 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657, 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799, 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889, 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951, 4957, 4967, 4969, 4973, 4987, 4993, 4999, 0 }; static int no_of_small_prime_numbers = DIM (small_prime_numbers) - 1; /* An object and a list to build up a global pool of primes. See save_pool_prime and get_pool_prime. */ struct primepool_s { struct primepool_s *next; gcry_mpi_t prime; /* If this is NULL the entry is not used. */ unsigned int nbits; gcry_random_level_t randomlevel; }; struct primepool_s *primepool; /* Mutex used to protect access to the primepool. */ GPGRT_LOCK_DEFINE (primepool_lock); gcry_err_code_t _gcry_primegen_init (void) { /* This function was formerly used to initialize the primepool Mutex. This has been replace by a static initialization. */ return 0; } /* Save PRIME which has been generated at RANDOMLEVEL for later use. Needs to be called while primepool_lock is being hold. Note that PRIME should be considered released after calling this function. */ static void save_pool_prime (gcry_mpi_t prime, gcry_random_level_t randomlevel) { struct primepool_s *item, *item2; size_t n; for (n=0, item = primepool; item; item = item->next, n++) if (!item->prime) break; if (!item && n > 100) { /* Remove some of the entries. Our strategy is removing the last third from the list. */ int i; for (i=0, item2 = primepool; item2; item2 = item2->next) { if (i >= n/3*2) { _gcry_mpi_release (item2->prime); item2->prime = NULL; if (!item) item = item2; } } } if (!item) { item = xtrycalloc (1, sizeof *item); if (!item) { /* Out of memory. Silently giving up. */ _gcry_mpi_release (prime); return; } item->next = primepool; primepool = item; } item->prime = prime; item->nbits = mpi_get_nbits (prime); item->randomlevel = randomlevel; } /* Return a prime for the prime pool or NULL if none has been found. The prime needs to match NBITS and randomlevel. This function needs to be called with the primepool_look is being hold. */ static gcry_mpi_t get_pool_prime (unsigned int nbits, gcry_random_level_t randomlevel) { struct primepool_s *item; for (item = primepool; item; item = item->next) if (item->prime && item->nbits == nbits && item->randomlevel == randomlevel) { gcry_mpi_t prime = item->prime; item->prime = NULL; gcry_assert (nbits == mpi_get_nbits (prime)); return prime; } return NULL; } void _gcry_register_primegen_progress ( void (*cb)(void *,const char*,int,int,int), void *cb_data ) { progress_cb = cb; progress_cb_data = cb_data; } static void progress( int c ) { if ( progress_cb ) progress_cb ( progress_cb_data, "primegen", c, 0, 0 ); } /**************** * Generate a prime number (stored in secure memory) */ gcry_mpi_t _gcry_generate_secret_prime (unsigned int nbits, gcry_random_level_t random_level, int (*extra_check)(void*, gcry_mpi_t), void *extra_check_arg) { gcry_mpi_t prime; prime = gen_prime (nbits, 1, random_level, extra_check, extra_check_arg); progress('\n'); return prime; } /* Generate a prime number which may be public, i.e. not allocated in secure memory. */ gcry_mpi_t _gcry_generate_public_prime (unsigned int nbits, gcry_random_level_t random_level, int (*extra_check)(void*, gcry_mpi_t), void *extra_check_arg) { gcry_mpi_t prime; prime = gen_prime (nbits, 0, random_level, extra_check, extra_check_arg); progress('\n'); return prime; } /* Core prime generation function. The algorithm used to generate practically save primes is due to Lim and Lee as described in the CRYPTO '97 proceedings (ISBN3540633847) page 260. NEED_Q_FACTOR: If true make sure that at least one factor is of size qbits. This is for example required for DSA. PRIME_GENERATED: Adresss of a variable where the resulting prime number will be stored. PBITS: Requested size of the prime number. At least 48. QBITS: One factor of the prime needs to be of this size. Maybe 0 if this is not required. See also MODE. G: If not NULL an MPI which will receive a generator for the prime for use with Elgamal. RET_FACTORS: if not NULL, an array with all factors are stored at that address. ALL_FACTORS: If set to true all factors of prime-1 are returned. RANDOMLEVEL: How strong should the random numers be. FLAGS: Prime generation bit flags. Currently supported: GCRY_PRIME_FLAG_SECRET - The prime needs to be kept secret. CB_FUNC, CB_ARG: Callback to be used for extra checks. */ static gcry_err_code_t prime_generate_internal (int need_q_factor, gcry_mpi_t *prime_generated, unsigned int pbits, unsigned int qbits, gcry_mpi_t g, gcry_mpi_t **ret_factors, gcry_random_level_t randomlevel, unsigned int flags, int all_factors, gcry_prime_check_func_t cb_func, void *cb_arg) { gcry_err_code_t err = 0; gcry_mpi_t *factors_new = NULL; /* Factors to return to the caller. */ gcry_mpi_t *factors = NULL; /* Current factors. */ gcry_random_level_t poolrandomlevel; /* Random level used for pool primes. */ gcry_mpi_t *pool = NULL; /* Pool of primes. */ int *pool_in_use = NULL; /* Array with currently used POOL elements. */ unsigned char *perms = NULL; /* Permutations of POOL. */ gcry_mpi_t q_factor = NULL; /* Used if QBITS is non-zero. */ unsigned int fbits = 0; /* Length of prime factors. */ unsigned int n = 0; /* Number of factors. */ unsigned int m = 0; /* Number of primes in pool. */ gcry_mpi_t q = NULL; /* First prime factor. */ gcry_mpi_t prime = NULL; /* Prime candidate. */ unsigned int nprime = 0; /* Bits of PRIME. */ unsigned int req_qbits; /* The original QBITS value. */ gcry_mpi_t val_2; /* For check_prime(). */ int is_locked = 0; /* Flag to help unlocking the primepool. */ unsigned int is_secret = (flags & GCRY_PRIME_FLAG_SECRET); unsigned int count1 = 0, count2 = 0; unsigned int i = 0, j = 0; if (pbits < 48) return GPG_ERR_INV_ARG; /* We won't use a too strong random elvel for the pooled subprimes. */ poolrandomlevel = (randomlevel > GCRY_STRONG_RANDOM? GCRY_STRONG_RANDOM : randomlevel); /* If QBITS is not given, assume a reasonable value. */ if (!qbits) qbits = pbits / 3; req_qbits = qbits; /* Find number of needed prime factors N. */ for (n = 1; (pbits - qbits - 1) / n >= qbits; n++) ; n--; val_2 = mpi_alloc_set_ui (2); if ((! n) || ((need_q_factor) && (n < 2))) { err = GPG_ERR_INV_ARG; goto leave; } if (need_q_factor) { n--; /* Need one factor less because we want a specific Q-FACTOR. */ fbits = (pbits - 2 * req_qbits -1) / n; qbits = pbits - req_qbits - n * fbits; } else { fbits = (pbits - req_qbits -1) / n; qbits = pbits - n * fbits; } if (DBG_CIPHER) log_debug ("gen prime: pbits=%u qbits=%u fbits=%u/%u n=%d\n", pbits, req_qbits, qbits, fbits, n); /* Allocate an integer to old the new prime. */ prime = mpi_new (pbits); /* Generate first prime factor. */ q = gen_prime (qbits, is_secret, randomlevel, NULL, NULL); /* Generate a specific Q-Factor if requested. */ if (need_q_factor) q_factor = gen_prime (req_qbits, is_secret, randomlevel, NULL, NULL); /* Allocate an array to hold all factors + 2 for later usage. */ factors = xtrycalloc (n + 2, sizeof (*factors)); if (!factors) { err = gpg_err_code_from_errno (errno); goto leave; } /* Allocate an array to track pool usage. */ pool_in_use = xtrymalloc (n * sizeof *pool_in_use); if (!pool_in_use) { err = gpg_err_code_from_errno (errno); goto leave; } for (i=0; i < n; i++) pool_in_use[i] = -1; /* Make a pool of 3n+5 primes (this is an arbitrary value). We require at least 30 primes for are useful selection process. Fixme: We need to research the best formula for sizing the pool. */ m = n * 3 + 5; if (need_q_factor) /* Need some more in this case. */ m += 5; if (m < 30) m = 30; pool = xtrycalloc (m , sizeof (*pool)); if (! pool) { err = gpg_err_code_from_errno (errno); goto leave; } /* Permutate over the pool of primes until we find a prime of the requested length. */ do { next_try: for (i=0; i < n; i++) pool_in_use[i] = -1; if (!perms) { /* Allocate new primes. This is done right at the beginning of the loop and if we have later run out of primes. */ for (i = 0; i < m; i++) { mpi_free (pool[i]); pool[i] = NULL; } /* Init m_out_of_n(). */ perms = xtrycalloc (1, m); if (!perms) { err = gpg_err_code_from_errno (errno); goto leave; } err = gpgrt_lock_lock (&primepool_lock); if (err) goto leave; is_locked = 1; for (i = 0; i < n; i++) { perms[i] = 1; /* At a maximum we use strong random for the factors. This saves us a lot of entropy. Given that Q and possible Q-factor are also used in the final prime this should be acceptable. We also don't allocate in secure memory to save on that scare resource too. If Q has been allocated in secure memory, the final prime will be saved there anyway. This is because our MPI routines take care of that. GnuPG has worked this way ever since. */ pool[i] = NULL; if (is_locked) { pool[i] = get_pool_prime (fbits, poolrandomlevel); if (!pool[i]) { err = gpgrt_lock_unlock (&primepool_lock); if (err) goto leave; is_locked = 0; } } if (!pool[i]) pool[i] = gen_prime (fbits, 0, poolrandomlevel, NULL, NULL); pool_in_use[i] = i; factors[i] = pool[i]; } if (is_locked && (err = gpgrt_lock_unlock (&primepool_lock))) goto leave; is_locked = 0; } else { /* Get next permutation. */ m_out_of_n ( (char*)perms, n, m); if ((err = gpgrt_lock_lock (&primepool_lock))) goto leave; is_locked = 1; for (i = j = 0; (i < m) && (j < n); i++) if (perms[i]) { /* If the subprime has not yet beed generated do it now. */ if (!pool[i] && is_locked) { pool[i] = get_pool_prime (fbits, poolrandomlevel); if (!pool[i]) { if ((err = gpgrt_lock_unlock (&primepool_lock))) goto leave; is_locked = 0; } } if (!pool[i]) pool[i] = gen_prime (fbits, 0, poolrandomlevel, NULL, NULL); pool_in_use[j] = i; factors[j++] = pool[i]; } if (is_locked && (err = gpgrt_lock_unlock (&primepool_lock))) goto leave; is_locked = 0; if (i == n) { /* Ran out of permutations: Allocate new primes. */ xfree (perms); perms = NULL; progress ('!'); goto next_try; } } /* Generate next prime candidate: p = 2 * q [ * q_factor] * factor_0 * factor_1 * ... * factor_n + 1. */ mpi_set (prime, q); mpi_mul_ui (prime, prime, 2); if (need_q_factor) mpi_mul (prime, prime, q_factor); for(i = 0; i < n; i++) mpi_mul (prime, prime, factors[i]); mpi_add_ui (prime, prime, 1); nprime = mpi_get_nbits (prime); if (nprime < pbits) { if (++count1 > 20) { count1 = 0; qbits++; progress('>'); mpi_free (q); q = gen_prime (qbits, is_secret, randomlevel, NULL, NULL); goto next_try; } } else count1 = 0; if (nprime > pbits) { if (++count2 > 20) { count2 = 0; qbits--; progress('<'); mpi_free (q); q = gen_prime (qbits, is_secret, randomlevel, NULL, NULL); goto next_try; } } else count2 = 0; } while (! ((nprime == pbits) && check_prime (prime, val_2, 5, cb_func, cb_arg))); if (DBG_CIPHER) { progress ('\n'); log_mpidump ("prime ", prime); log_mpidump ("factor q", q); if (need_q_factor) log_mpidump ("factor q0", q_factor); for (i = 0; i < n; i++) log_mpidump ("factor pi", factors[i]); log_debug ("bit sizes: prime=%u, q=%u", mpi_get_nbits (prime), mpi_get_nbits (q)); if (need_q_factor) log_printf (", q0=%u", mpi_get_nbits (q_factor)); for (i = 0; i < n; i++) log_printf (", p%d=%u", i, mpi_get_nbits (factors[i])); log_printf ("\n"); } if (ret_factors) { /* Caller wants the factors. */ factors_new = xtrycalloc (n + 4, sizeof (*factors_new)); if (! factors_new) { err = gpg_err_code_from_errno (errno); goto leave; } if (all_factors) { i = 0; factors_new[i++] = mpi_set_ui (NULL, 2); factors_new[i++] = mpi_copy (q); if (need_q_factor) factors_new[i++] = mpi_copy (q_factor); for(j=0; j < n; j++) factors_new[i++] = mpi_copy (factors[j]); } else { i = 0; if (need_q_factor) { factors_new[i++] = mpi_copy (q_factor); for (; i <= n; i++) factors_new[i] = mpi_copy (factors[i]); } else for (; i < n; i++ ) factors_new[i] = mpi_copy (factors[i]); } } if (g && need_q_factor) err = GPG_ERR_NOT_IMPLEMENTED; else if (g) { /* Create a generator (start with 3). */ gcry_mpi_t tmp = mpi_alloc (mpi_get_nlimbs (prime)); gcry_mpi_t b = mpi_alloc (mpi_get_nlimbs (prime)); gcry_mpi_t pmin1 = mpi_alloc (mpi_get_nlimbs (prime)); factors[n] = q; factors[n + 1] = mpi_alloc_set_ui (2); mpi_sub_ui (pmin1, prime, 1); mpi_set_ui (g, 2); do { mpi_add_ui (g, g, 1); if (DBG_CIPHER) log_printmpi ("checking g", g); else progress('^'); for (i = 0; i < n + 2; i++) { mpi_fdiv_q (tmp, pmin1, factors[i]); /* No mpi_pow(), but it is okay to use this with mod prime. */ mpi_powm (b, g, tmp, prime); if (! mpi_cmp_ui (b, 1)) break; } if (DBG_CIPHER) progress('\n'); } while (i < n + 2); mpi_free (factors[n+1]); mpi_free (tmp); mpi_free (b); mpi_free (pmin1); } if (! DBG_CIPHER) progress ('\n'); leave: if (pool) { is_locked = !gpgrt_lock_lock (&primepool_lock); for(i = 0; i < m; i++) { if (pool[i]) { for (j=0; j < n; j++) if (pool_in_use[j] == i) break; if (j == n && is_locked) { /* This pooled subprime has not been used. */ save_pool_prime (pool[i], poolrandomlevel); } else mpi_free (pool[i]); } } if (is_locked) err = gpgrt_lock_unlock (&primepool_lock); is_locked = 0; xfree (pool); } xfree (pool_in_use); if (factors) xfree (factors); /* Factors are shallow copies. */ if (perms) xfree (perms); mpi_free (val_2); mpi_free (q); mpi_free (q_factor); if (! err) { *prime_generated = prime; if (ret_factors) *ret_factors = factors_new; } else { if (factors_new) { for (i = 0; factors_new[i]; i++) mpi_free (factors_new[i]); xfree (factors_new); } mpi_free (prime); } return err; } /* Generate a prime used for discrete logarithm algorithms; i.e. this prime will be public and no strong random is required. On success R_PRIME receives a new MPI with the prime. On error R_PRIME is set to NULL and an error code is returned. If RET_FACTORS is not NULL it is set to an allocated array of factors on success or to NULL on error. */ gcry_err_code_t _gcry_generate_elg_prime (int mode, unsigned pbits, unsigned qbits, gcry_mpi_t g, gcry_mpi_t *r_prime, gcry_mpi_t **ret_factors) { *r_prime = NULL; if (ret_factors) *ret_factors = NULL; return prime_generate_internal ((mode == 1), r_prime, pbits, qbits, g, ret_factors, GCRY_WEAK_RANDOM, 0, 0, NULL, NULL); } static gcry_mpi_t gen_prime (unsigned int nbits, int secret, int randomlevel, int (*extra_check)(void *, gcry_mpi_t), void *extra_check_arg) { gcry_mpi_t prime, ptest, pminus1, val_2, val_3, result; int i; unsigned int x, step; unsigned int count1, count2; int *mods; /* if ( DBG_CIPHER ) */ /* log_debug ("generate a prime of %u bits ", nbits ); */ if (nbits < 16) log_fatal ("can't generate a prime with less than %d bits\n", 16); mods = xmalloc (no_of_small_prime_numbers * sizeof *mods); /* Make nbits fit into gcry_mpi_t implementation. */ val_2 = mpi_alloc_set_ui( 2 ); val_3 = mpi_alloc_set_ui( 3); prime = secret? mpi_snew (nbits): mpi_new (nbits); result = mpi_alloc_like( prime ); pminus1= mpi_alloc_like( prime ); ptest = mpi_alloc_like( prime ); count1 = count2 = 0; for (;;) { /* try forvever */ int dotcount=0; /* generate a random number */ _gcry_mpi_randomize( prime, nbits, randomlevel ); /* Set high order bit to 1, set low order bit to 1. If we are generating a secret prime we are most probably doing that for RSA, to make sure that the modulus does have the requested key size we set the 2 high order bits. */ mpi_set_highbit (prime, nbits-1); if (secret) mpi_set_bit (prime, nbits-2); mpi_set_bit(prime, 0); /* Calculate all remainders. */ for (i=0; (x = small_prime_numbers[i]); i++ ) mods[i] = mpi_fdiv_r_ui(NULL, prime, x); /* Now try some primes starting with prime. */ for(step=0; step < 20000; step += 2 ) { /* Check against all the small primes we have in mods. */ count1++; for (i=0; (x = small_prime_numbers[i]); i++ ) { while ( mods[i] + step >= x ) mods[i] -= x; if ( !(mods[i] + step) ) break; } if ( x ) continue; /* Found a multiple of an already known prime. */ mpi_add_ui( ptest, prime, step ); /* Do a fast Fermat test now. */ count2++; mpi_sub_ui( pminus1, ptest, 1); mpi_powm( result, val_2, pminus1, ptest ); if ( !mpi_cmp_ui( result, 1 ) ) { /* Not composite, perform stronger tests */ if (is_prime(ptest, 5, &count2 )) { if (!mpi_test_bit( ptest, nbits-1-secret )) { progress('\n'); log_debug ("overflow in prime generation\n"); break; /* Stop loop, continue with a new prime. */ } if (extra_check && extra_check (extra_check_arg, ptest)) { /* The extra check told us that this prime is not of the caller's taste. */ progress ('/'); } else { /* Got it. */ mpi_free(val_2); mpi_free(val_3); mpi_free(result); mpi_free(pminus1); mpi_free(prime); xfree(mods); return ptest; } } } if (++dotcount == 10 ) { progress('.'); dotcount = 0; } } progress(':'); /* restart with a new random value */ } } /**************** * Returns: true if this may be a prime * RM_ROUNDS gives the number of Rabin-Miller tests to run. */ static int check_prime( gcry_mpi_t prime, gcry_mpi_t val_2, int rm_rounds, gcry_prime_check_func_t cb_func, void *cb_arg) { int i; unsigned int x; unsigned int count=0; /* Check against small primes. */ for (i=0; (x = small_prime_numbers[i]); i++ ) { if ( mpi_divisible_ui( prime, x ) ) return !mpi_cmp_ui (prime, x); } /* A quick Fermat test. */ { gcry_mpi_t result = mpi_alloc_like( prime ); gcry_mpi_t pminus1 = mpi_alloc_like( prime ); mpi_sub_ui( pminus1, prime, 1); mpi_powm( result, val_2, pminus1, prime ); mpi_free( pminus1 ); if ( mpi_cmp_ui( result, 1 ) ) { /* Is composite. */ mpi_free( result ); progress('.'); return 0; } mpi_free( result ); } if (!cb_func || cb_func (cb_arg, GCRY_PRIME_CHECK_AT_MAYBE_PRIME, prime)) { /* Perform stronger tests. */ if ( is_prime( prime, rm_rounds, &count ) ) { if (!cb_func || cb_func (cb_arg, GCRY_PRIME_CHECK_AT_GOT_PRIME, prime)) return 1; /* Probably a prime. */ } } progress('.'); return 0; } /* * Return true if n is probably a prime */ static int is_prime (gcry_mpi_t n, int steps, unsigned int *count) { gcry_mpi_t x = mpi_alloc( mpi_get_nlimbs( n ) ); gcry_mpi_t y = mpi_alloc( mpi_get_nlimbs( n ) ); gcry_mpi_t z = mpi_alloc( mpi_get_nlimbs( n ) ); gcry_mpi_t nminus1 = mpi_alloc( mpi_get_nlimbs( n ) ); gcry_mpi_t a2 = mpi_alloc_set_ui( 2 ); gcry_mpi_t q; unsigned i, j, k; int rc = 0; unsigned nbits = mpi_get_nbits( n ); if (steps < 5) /* Make sure that we do at least 5 rounds. */ steps = 5; mpi_sub_ui( nminus1, n, 1 ); /* Find q and k, so that n = 1 + 2^k * q . */ q = mpi_copy ( nminus1 ); k = mpi_trailing_zeros ( q ); mpi_tdiv_q_2exp (q, q, k); for (i=0 ; i < steps; i++ ) { ++*count; if( !i ) { mpi_set_ui( x, 2 ); } else { _gcry_mpi_randomize( x, nbits, GCRY_WEAK_RANDOM ); /* Make sure that the number is smaller than the prime and keep the randomness of the high bit. */ if ( mpi_test_bit ( x, nbits-2) ) { mpi_set_highbit ( x, nbits-2); /* Clear all higher bits. */ } else { mpi_set_highbit( x, nbits-2 ); mpi_clear_bit( x, nbits-2 ); } gcry_assert (mpi_cmp (x, nminus1) < 0 && mpi_cmp_ui (x, 1) > 0); } mpi_powm ( y, x, q, n); if ( mpi_cmp_ui(y, 1) && mpi_cmp( y, nminus1 ) ) { for ( j=1; j < k && mpi_cmp( y, nminus1 ); j++ ) { mpi_powm(y, y, a2, n); if( !mpi_cmp_ui( y, 1 ) ) goto leave; /* Not a prime. */ } if (mpi_cmp( y, nminus1 ) ) goto leave; /* Not a prime. */ } progress('+'); } rc = 1; /* May be a prime. */ leave: mpi_free( x ); mpi_free( y ); mpi_free( z ); mpi_free( nminus1 ); mpi_free( q ); mpi_free( a2 ); return rc; } /* Given ARRAY of size N with M elements set to true produce a modified array with the next permutation of M elements. Note, that ARRAY is used in a one-bit-per-byte approach. To detected the last permutation it is useful to initialize the array with the first M element set to true and use this test: m_out_of_n (array, m, n); for (i = j = 0; i < n && j < m; i++) if (array[i]) j++; if (j == m) goto ready; This code is based on the algorithm 452 from the "Collected Algorithms From ACM, Volume II" by C. N. Liu and D. T. Tang. */ static void m_out_of_n ( char *array, int m, int n ) { int i=0, i1=0, j=0, jp=0, j1=0, k1=0, k2=0; if( !m || m >= n ) return; /* Need to handle this simple case separately. */ if( m == 1 ) { for (i=0; i < n; i++ ) { if ( array[i] ) { array[i++] = 0; if( i >= n ) i = 0; array[i] = 1; return; } } BUG(); } for (j=1; j < n; j++ ) { if ( array[n-1] == array[n-j-1]) continue; j1 = j; break; } if ( (m & 1) ) { /* M is odd. */ if( array[n-1] ) { if( j1 & 1 ) { k1 = n - j1; k2 = k1+2; if( k2 > n ) k2 = n; goto leave; } goto scan; } k2 = n - j1 - 1; if( k2 == 0 ) { k1 = i; k2 = n - j1; } else if( array[k2] && array[k2-1] ) k1 = n; else k1 = k2 + 1; } else { /* M is even. */ if( !array[n-1] ) { k1 = n - j1; k2 = k1 + 1; goto leave; } if( !(j1 & 1) ) { k1 = n - j1; k2 = k1+2; if( k2 > n ) k2 = n; goto leave; } scan: jp = n - j1 - 1; for (i=1; i <= jp; i++ ) { i1 = jp + 2 - i; if( array[i1-1] ) { if( array[i1-2] ) { k1 = i1 - 1; k2 = n - j1; } else { k1 = i1 - 1; k2 = n + 1 - j1; } goto leave; } } k1 = 1; k2 = n + 1 - m; } leave: /* Now complement the two selected bits. */ array[k1-1] = !array[k1-1]; array[k2-1] = !array[k2-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_err_code_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) { gcry_err_code_t rc = 0; gcry_mpi_t *factors_generated = NULL; gcry_mpi_t prime_generated = NULL; unsigned int mode = 0; if (!prime) return GPG_ERR_INV_ARG; *prime = NULL; if (flags & GCRY_PRIME_FLAG_SPECIAL_FACTOR) mode = 1; /* Generate. */ rc = prime_generate_internal ((mode==1), &prime_generated, prime_bits, factor_bits, NULL, factors? &factors_generated : NULL, random_level, flags, 1, cb_func, cb_arg); if (!rc && cb_func) { /* Additional check. */ if ( !cb_func (cb_arg, GCRY_PRIME_CHECK_AT_FINISH, prime_generated)) { /* Failed, deallocate resources. */ unsigned int i; mpi_free (prime_generated); if (factors) { for (i = 0; factors_generated[i]; i++) mpi_free (factors_generated[i]); xfree (factors_generated); } rc = GPG_ERR_GENERAL; } } if (!rc) { if (factors) *factors = factors_generated; *prime = prime_generated; } return rc; } /* Check whether the number X is prime. */ gcry_err_code_t _gcry_prime_check (gcry_mpi_t x, unsigned int flags) { (void)flags; switch (mpi_cmp_ui (x, 2)) { case 0: return 0; /* 2 is a prime */ case -1: return GPG_ERR_NO_PRIME; /* Only numbers > 1 are primes. */ } /* We use 64 rounds because the prime we are going to test is not guaranteed to be a random one. */ if (check_prime (x, mpi_const (MPI_C_TWO), 64, NULL, NULL)) return 0; return GPG_ERR_NO_PRIME; } /* Check whether the number X is prime according to FIPS 186-4 table C.2. */ gcry_err_code_t _gcry_fips186_4_prime_check (gcry_mpi_t x, unsigned int bits) { gcry_err_code_t ec = GPG_ERR_NO_ERROR; switch (mpi_cmp_ui (x, 2)) { case 0: return ec; /* 2 is a prime */ case -1: return GPG_ERR_NO_PRIME; /* Only numbers > 1 are primes. */ } /* We use 5 or 4 rounds as specified in table C.2 */ if (! check_prime (x, mpi_const (MPI_C_TWO), bits > 1024 ? 4 : 5, NULL, NULL)) ec = GPG_ERR_NO_PRIME; return ec; } /* 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 s atart for the search. Returns 0 on success.*/ gcry_err_code_t _gcry_prime_group_generator (gcry_mpi_t *r_g, gcry_mpi_t prime, gcry_mpi_t *factors, gcry_mpi_t start_g) { gcry_mpi_t tmp, b, pmin1, g; int first, i, n; if (!r_g) return GPG_ERR_INV_ARG; *r_g = NULL; if (!factors || !prime) return GPG_ERR_INV_ARG; for (n=0; factors[n]; n++) ; if (n < 2) return GPG_ERR_INV_ARG; tmp = mpi_new (0); b = mpi_new (0); pmin1 = mpi_new (0); g = start_g? mpi_copy (start_g) : mpi_set_ui (NULL, 3); /* Extra sanity check - usually disabled. */ /* mpi_set (tmp, factors[0]); */ /* for(i = 1; i < n; i++) */ /* mpi_mul (tmp, tmp, factors[i]); */ /* mpi_add_ui (tmp, tmp, 1); */ /* if (mpi_cmp (prime, tmp)) */ /* return gpg_error (GPG_ERR_INV_ARG); */ mpi_sub_ui (pmin1, prime, 1); first = 1; do { if (first) first = 0; else mpi_add_ui (g, g, 1); if (DBG_CIPHER) log_printmpi ("checking g", g); else progress('^'); for (i = 0; i < n; i++) { mpi_fdiv_q (tmp, pmin1, factors[i]); mpi_powm (b, g, tmp, prime); if (! mpi_cmp_ui (b, 1)) break; } if (DBG_CIPHER) progress('\n'); } while (i < n); _gcry_mpi_release (tmp); _gcry_mpi_release (b); _gcry_mpi_release (pmin1); *r_g = g; return 0; } /* Convenience function to release the factors array. */ void _gcry_prime_release_factors (gcry_mpi_t *factors) { if (factors) { int i; for (i=0; factors[i]; i++) mpi_free (factors[i]); xfree (factors); } } /* Helper for _gcry_derive_x931_prime. */ static gcry_mpi_t find_x931_prime (const gcry_mpi_t pfirst) { gcry_mpi_t val_2 = mpi_alloc_set_ui (2); gcry_mpi_t prime; prime = mpi_copy (pfirst); /* If P is even add 1. */ mpi_set_bit (prime, 0); /* We use 64 Rabin-Miller rounds which is better and thus - sufficient. We do not have a Lucas test implementaion thus we + sufficient. We do not have a Lucas test implementation thus we can't do it in the X9.31 preferred way of running a few Rabin-Miller followed by one Lucas test. */ while ( !check_prime (prime, val_2, 64, NULL, NULL) ) mpi_add_ui (prime, prime, 2); mpi_free (val_2); return prime; } /* Generate a prime using the algorithm from X9.31 appendix B.4. This function requires that the provided public exponent E is odd. XP, XP1 and XP2 are the seed values. All values are mandatory. On success the prime is returned. If R_P1 or R_P2 are given the internal values P1 and P2 are saved at these addresses. On error NULL is returned. */ gcry_mpi_t _gcry_derive_x931_prime (const gcry_mpi_t xp, const gcry_mpi_t xp1, const gcry_mpi_t xp2, const gcry_mpi_t e, gcry_mpi_t *r_p1, gcry_mpi_t *r_p2) { gcry_mpi_t p1, p2, p1p2, yp0; if (!xp || !xp1 || !xp2) return NULL; if (!e || !mpi_test_bit (e, 0)) return NULL; /* We support only odd values for E. */ p1 = find_x931_prime (xp1); p2 = find_x931_prime (xp2); p1p2 = mpi_alloc_like (xp); mpi_mul (p1p2, p1, p2); { gcry_mpi_t r1, tmp; /* r1 = (p2^{-1} mod p1)p2 - (p1^{-1} mod p2) */ tmp = mpi_alloc_like (p1); mpi_invm (tmp, p2, p1); mpi_mul (tmp, tmp, p2); r1 = tmp; tmp = mpi_alloc_like (p2); mpi_invm (tmp, p1, p2); mpi_mul (tmp, tmp, p1); mpi_sub (r1, r1, tmp); /* Fixup a negative value. */ if (mpi_has_sign (r1)) mpi_add (r1, r1, p1p2); /* yp0 = xp + (r1 - xp mod p1*p2) */ yp0 = tmp; tmp = NULL; mpi_subm (yp0, r1, xp, p1p2); mpi_add (yp0, yp0, xp); mpi_free (r1); /* Fixup a negative value. */ if (mpi_cmp (yp0, xp) < 0 ) mpi_add (yp0, yp0, p1p2); } /* yp0 is now the first integer greater than xp with p1 being a large prime factor of yp0-1 and p2 a large prime factor of yp0+1. */ /* Note that the first example from X9.31 (D.1.1) which uses (Xq1 #1A5CF72EE770DE50CB09ACCEA9#) (Xq2 #134E4CAA16D2350A21D775C404#) (Xq #CC1092495D867E64065DEE3E7955F2EBC7D47A2D 7C9953388F97DDDC3E1CA19C35CA659EDC2FC325 6D29C2627479C086A699A49C4C9CEE7EF7BD1B34 321DE34A#)))) returns an yp0 of #CC1092495D867E64065DEE3E7955F2EBC7D47A2D 7C9953388F97DDDC3E1CA19C35CA659EDC2FC4E3 BF20CB896EE37E098A906313271422162CB6C642 75C1201F# and not #CC1092495D867E64065DEE3E7955F2EBC7D47A2D 7C9953388F97DDDC3E1CA19C35CA659EDC2FC2E6 C88FE299D52D78BE405A97E01FD71DD7819ECB91 FA85A076# as stated in the standard. This seems to be a bug in X9.31. */ { gcry_mpi_t val_2 = mpi_alloc_set_ui (2); gcry_mpi_t gcdtmp = mpi_alloc_like (yp0); int gcdres; mpi_sub_ui (p1p2, p1p2, 1); /* Adjust for loop body. */ mpi_sub_ui (yp0, yp0, 1); /* Ditto. */ for (;;) { gcdres = mpi_gcd (gcdtmp, e, yp0); mpi_add_ui (yp0, yp0, 1); if (!gcdres) progress ('/'); /* gcd (e, yp0-1) != 1 */ else if (check_prime (yp0, val_2, 64, NULL, NULL)) break; /* Found. */ /* We add p1p2-1 because yp0 is incremented after the gcd test. */ mpi_add (yp0, yp0, p1p2); } mpi_free (gcdtmp); mpi_free (val_2); } mpi_free (p1p2); progress('\n'); if (r_p1) *r_p1 = p1; else mpi_free (p1); if (r_p2) *r_p2 = p2; else mpi_free (p2); return yp0; } /* Generate the two prime used for DSA using the algorithm specified in FIPS 186-2. PBITS is the desired length of the prime P and a QBITS the length of the prime Q. If SEED is not supplied and SEEDLEN is 0 the function generates an appropriate SEED. On success the generated primes are stored at R_Q and R_P, the counter value is stored at R_COUNTER and the seed actually used for generation is stored at R_SEED and R_SEEDVALUE. */ gpg_err_code_t _gcry_generate_fips186_2_prime (unsigned int pbits, unsigned int qbits, const void *seed, size_t seedlen, gcry_mpi_t *r_q, gcry_mpi_t *r_p, int *r_counter, void **r_seed, size_t *r_seedlen) { gpg_err_code_t ec; unsigned char seed_help_buffer[160/8]; /* Used to hold a generated SEED. */ unsigned char *seed_plus; /* Malloced buffer to hold SEED+x. */ unsigned char digest[160/8]; /* Helper buffer for SHA-1 digest. */ gcry_mpi_t val_2 = NULL; /* Helper for the prime test. */ gcry_mpi_t tmpval = NULL; /* Helper variable. */ int i; unsigned char value_u[160/8]; int value_n, value_b, value_k; int counter; gcry_mpi_t value_w = NULL; gcry_mpi_t value_x = NULL; gcry_mpi_t prime_q = NULL; gcry_mpi_t prime_p = NULL; /* FIPS 186-2 allows only for 1024/160 bit. */ if (pbits != 1024 || qbits != 160) return GPG_ERR_INV_KEYLEN; if (!seed && !seedlen) ; /* No seed value given: We are asked to generate it. */ else if (!seed || seedlen < qbits/8) return GPG_ERR_INV_ARG; /* Allocate a buffer to later compute SEED+some_increment. */ seed_plus = xtrymalloc (seedlen < 20? 20:seedlen); if (!seed_plus) { ec = gpg_err_code_from_syserror (); goto leave; } val_2 = mpi_alloc_set_ui (2); value_n = (pbits - 1) / qbits; value_b = (pbits - 1) - value_n * qbits; value_w = mpi_new (pbits); value_x = mpi_new (pbits); restart: /* Generate Q. */ for (;;) { /* Step 1: Generate a (new) seed unless one has been supplied. */ if (!seed) { seedlen = sizeof seed_help_buffer; _gcry_create_nonce (seed_help_buffer, seedlen); seed = seed_help_buffer; } /* Step 2: U = sha1(seed) ^ sha1((seed+1) mod 2^{qbits}) */ memcpy (seed_plus, seed, seedlen); for (i=seedlen-1; i >= 0; i--) { seed_plus[i]++; if (seed_plus[i]) break; } _gcry_md_hash_buffer (GCRY_MD_SHA1, value_u, seed, seedlen); _gcry_md_hash_buffer (GCRY_MD_SHA1, digest, seed_plus, seedlen); for (i=0; i < sizeof value_u; i++) value_u[i] ^= digest[i]; /* Step 3: Form q from U */ _gcry_mpi_release (prime_q); prime_q = NULL; ec = _gcry_mpi_scan (&prime_q, GCRYMPI_FMT_USG, value_u, sizeof value_u, NULL); if (ec) goto leave; mpi_set_highbit (prime_q, qbits-1 ); mpi_set_bit (prime_q, 0); /* Step 4: Test whether Q is prime using 64 round of Rabin-Miller. */ if (check_prime (prime_q, val_2, 64, NULL, NULL)) break; /* Yes, Q is prime. */ /* Step 5. */ seed = NULL; /* Force a new seed at Step 1. */ } /* Step 6. Note that we do no use an explicit offset but increment SEED_PLUS accordingly. SEED_PLUS is currently SEED+1. */ counter = 0; /* Generate P. */ prime_p = mpi_new (pbits); for (;;) { /* Step 7: For k = 0,...n let V_k = sha1(seed+offset+k) mod 2^{qbits} Step 8: W = V_0 + V_1*2^160 + ... + V_{n-1}*2^{(n-1)*160} + (V_{n} mod 2^b)*2^{n*160} */ mpi_set_ui (value_w, 0); for (value_k=0; value_k <= value_n; value_k++) { /* There is no need to have an explicit offset variable: In the first round we shall have an offset of 2, this is achieved by using SEED_PLUS which is already at SEED+1, thus we just need to increment it once again. The requirement for the next round is to update offset by N, which we implictly did at the end of this loop, and then to add one; this one is the same as in the first round. */ for (i=seedlen-1; i >= 0; i--) { seed_plus[i]++; if (seed_plus[i]) break; } _gcry_md_hash_buffer (GCRY_MD_SHA1, digest, seed_plus, seedlen); _gcry_mpi_release (tmpval); tmpval = NULL; ec = _gcry_mpi_scan (&tmpval, GCRYMPI_FMT_USG, digest, sizeof digest, NULL); if (ec) goto leave; if (value_k == value_n) mpi_clear_highbit (tmpval, value_b); /* (V_n mod 2^b) */ mpi_lshift (tmpval, tmpval, value_k*qbits); mpi_add (value_w, value_w, tmpval); } /* Step 8 continued: X = W + 2^{L-1} */ mpi_set_ui (value_x, 0); mpi_set_highbit (value_x, pbits-1); mpi_add (value_x, value_x, value_w); /* Step 9: c = X mod 2q, p = X - (c - 1) */ mpi_mul_2exp (tmpval, prime_q, 1); mpi_mod (tmpval, value_x, tmpval); mpi_sub_ui (tmpval, tmpval, 1); mpi_sub (prime_p, value_x, tmpval); /* Step 10: If p < 2^{L-1} skip the primality test. */ /* Step 11 and 12: Primality test. */ if (mpi_get_nbits (prime_p) >= pbits-1 && check_prime (prime_p, val_2, 64, NULL, NULL) ) break; /* Yes, P is prime, continue with Step 15. */ /* Step 13: counter = counter + 1, offset = offset + n + 1. */ counter++; /* Step 14: If counter >= 2^12 goto Step 1. */ if (counter >= 4096) goto restart; } /* Step 15: Save p, q, counter and seed. */ /* log_debug ("fips186-2 pbits p=%u q=%u counter=%d\n", */ /* mpi_get_nbits (prime_p), mpi_get_nbits (prime_q), counter); */ /* log_printhex("fips186-2 seed:", seed, seedlen); */ /* log_mpidump ("fips186-2 prime p", prime_p); */ /* log_mpidump ("fips186-2 prime q", prime_q); */ if (r_q) { *r_q = prime_q; prime_q = NULL; } if (r_p) { *r_p = prime_p; prime_p = NULL; } if (r_counter) *r_counter = counter; if (r_seed && r_seedlen) { memcpy (seed_plus, seed, seedlen); *r_seed = seed_plus; seed_plus = NULL; *r_seedlen = seedlen; } leave: _gcry_mpi_release (tmpval); _gcry_mpi_release (value_x); _gcry_mpi_release (value_w); _gcry_mpi_release (prime_p); _gcry_mpi_release (prime_q); xfree (seed_plus); _gcry_mpi_release (val_2); return ec; } /* WARNING: The code below has not yet been tested! * * Generate the two prime used for DSA using the algorithm specified * in FIPS 186-3, A.1.1.2. PBITS is the desired length of the prime P * and a QBITS the length of the prime Q. If SEED is not supplied and * SEEDLEN is 0 the function generates an appropriate SEED. On * success the generated primes are stored at R_Q and R_P, the counter * value is stored at R_COUNTER and the seed actually used for * generation is stored at R_SEED and R_SEEDVALUE. The hash algorithm * used is stored at R_HASHALGO. * * Note that this function is very similar to the fips186_2 code. Due * to the minor differences, other buffer sizes and for documentarion, * we use a separate function. */ gpg_err_code_t _gcry_generate_fips186_3_prime (unsigned int pbits, unsigned int qbits, const void *seed, size_t seedlen, gcry_mpi_t *r_q, gcry_mpi_t *r_p, int *r_counter, void **r_seed, size_t *r_seedlen, int *r_hashalgo) { gpg_err_code_t ec; unsigned char seed_help_buffer[256/8]; /* Used to hold a generated SEED. */ unsigned char *seed_plus; /* Malloced buffer to hold SEED+x. */ unsigned char digest[256/8]; /* Helper buffer for SHA-2 digest. */ gcry_mpi_t val_2 = NULL; /* Helper for the prime test. */ gcry_mpi_t tmpval = NULL; /* Helper variable. */ int hashalgo; /* The id of the Approved Hash Function. */ int i; unsigned char value_u[256/8]; int value_n, value_b, value_j; int counter; gcry_mpi_t value_w = NULL; gcry_mpi_t value_x = NULL; gcry_mpi_t prime_q = NULL; gcry_mpi_t prime_p = NULL; gcry_assert (sizeof seed_help_buffer == sizeof digest && sizeof seed_help_buffer == sizeof value_u); /* Step 1: Check the requested prime lengths. */ /* Note that due to the size of our buffers QBITS is limited to 256. */ if (pbits == 2048 && qbits == 224) hashalgo = GCRY_MD_SHA224; else if (pbits == 2048 && qbits == 256) hashalgo = GCRY_MD_SHA256; else if (pbits == 3072 && qbits == 256) hashalgo = GCRY_MD_SHA256; else return GPG_ERR_INV_KEYLEN; /* Also check that the hash algorithm is available. */ ec = _gcry_md_test_algo (hashalgo); if (ec) return ec; gcry_assert (qbits/8 <= sizeof digest); gcry_assert (_gcry_md_get_algo_dlen (hashalgo) == qbits/8); /* Step 2: Check seedlen. */ if (!seed && !seedlen) ; /* No seed value given: We are asked to generate it. */ else if (!seed || seedlen < qbits/8) return GPG_ERR_INV_ARG; /* Allocate a buffer to later compute SEED+some_increment and a few helper variables. */ seed_plus = xtrymalloc (seedlen < sizeof seed_help_buffer? sizeof seed_help_buffer : seedlen); if (!seed_plus) { ec = gpg_err_code_from_syserror (); goto leave; } val_2 = mpi_alloc_set_ui (2); value_w = mpi_new (pbits); value_x = mpi_new (pbits); /* Step 3: n = \lceil L / outlen \rceil - 1 */ value_n = (pbits + qbits - 1) / qbits - 1; /* Step 4: b = L - 1 - (n * outlen) */ value_b = pbits - 1 - (value_n * qbits); restart: /* Generate Q. */ for (;;) { /* Step 5: Generate a (new) seed unless one has been supplied. */ if (!seed) { seedlen = qbits/8; gcry_assert (seedlen <= sizeof seed_help_buffer); _gcry_create_nonce (seed_help_buffer, seedlen); seed = seed_help_buffer; } /* Step 6: U = hash(seed) */ _gcry_md_hash_buffer (hashalgo, value_u, seed, seedlen); /* Step 7: q = 2^{N-1} + U + 1 - (U mod 2) */ if ( !(value_u[qbits/8-1] & 0x01) ) { for (i=qbits/8-1; i >= 0; i--) { value_u[i]++; if (value_u[i]) break; } } _gcry_mpi_release (prime_q); prime_q = NULL; ec = _gcry_mpi_scan (&prime_q, GCRYMPI_FMT_USG, value_u, qbits/8, NULL); if (ec) goto leave; mpi_set_highbit (prime_q, qbits-1 ); /* Step 8: Test whether Q is prime using 64 round of Rabin-Miller. According to table C.1 this is sufficient for all supported prime sizes (i.e. up 3072/256). */ if (check_prime (prime_q, val_2, 64, NULL, NULL)) break; /* Yes, Q is prime. */ /* Step 8. */ seed = NULL; /* Force a new seed at Step 5. */ } /* Step 11. Note that we do no use an explicit offset but increment SEED_PLUS accordingly. */ memcpy (seed_plus, seed, seedlen); counter = 0; /* Generate P. */ prime_p = mpi_new (pbits); for (;;) { /* Step 11.1: For j = 0,...n let V_j = hash(seed+offset+j) Step 11.2: W = V_0 + V_1*2^outlen + ... + V_{n-1}*2^{(n-1)*outlen} + (V_{n} mod 2^b)*2^{n*outlen} */ mpi_set_ui (value_w, 0); for (value_j=0; value_j <= value_n; value_j++) { /* There is no need to have an explicit offset variable: In the first round we shall have an offset of 1 and a j of 0. This is achieved by incrementing SEED_PLUS here. For the next round offset is implicitly updated by using SEED_PLUS again. */ for (i=seedlen-1; i >= 0; i--) { seed_plus[i]++; if (seed_plus[i]) break; } _gcry_md_hash_buffer (hashalgo, digest, seed_plus, seedlen); _gcry_mpi_release (tmpval); tmpval = NULL; ec = _gcry_mpi_scan (&tmpval, GCRYMPI_FMT_USG, digest, qbits/8, NULL); if (ec) goto leave; if (value_j == value_n) mpi_clear_highbit (tmpval, value_b); /* (V_n mod 2^b) */ mpi_lshift (tmpval, tmpval, value_j*qbits); mpi_add (value_w, value_w, tmpval); } /* Step 11.3: X = W + 2^{L-1} */ mpi_set_ui (value_x, 0); mpi_set_highbit (value_x, pbits-1); mpi_add (value_x, value_x, value_w); /* Step 11.4: c = X mod 2q */ mpi_mul_2exp (tmpval, prime_q, 1); mpi_mod (tmpval, value_x, tmpval); /* Step 11.5: p = X - (c - 1) */ mpi_sub_ui (tmpval, tmpval, 1); mpi_sub (prime_p, value_x, tmpval); /* Step 11.6: If p < 2^{L-1} skip the primality test. */ /* Step 11.7 and 11.8: Primality test. */ if (mpi_get_nbits (prime_p) >= pbits-1 && check_prime (prime_p, val_2, 64, NULL, NULL) ) break; /* Yes, P is prime, continue with Step 15. */ /* Step 11.9: counter = counter + 1, offset = offset + n + 1. If counter >= 4L goto Step 5. */ counter++; if (counter >= 4*pbits) goto restart; } /* Step 12: Save p, q, counter and seed. */ /* log_debug ("fips186-3 pbits p=%u q=%u counter=%d\n", */ /* mpi_get_nbits (prime_p), mpi_get_nbits (prime_q), counter); */ /* log_printhex ("fips186-3 seed", seed, seedlen); */ /* log_printmpi ("fips186-3 p", prime_p); */ /* log_printmpi ("fips186-3 q", prime_q); */ if (r_q) { *r_q = prime_q; prime_q = NULL; } if (r_p) { *r_p = prime_p; prime_p = NULL; } if (r_counter) *r_counter = counter; if (r_seed && r_seedlen) { memcpy (seed_plus, seed, seedlen); *r_seed = seed_plus; seed_plus = NULL; *r_seedlen = seedlen; } if (r_hashalgo) *r_hashalgo = hashalgo; leave: _gcry_mpi_release (tmpval); _gcry_mpi_release (value_x); _gcry_mpi_release (value_w); _gcry_mpi_release (prime_p); _gcry_mpi_release (prime_q); xfree (seed_plus); _gcry_mpi_release (val_2); return ec; } diff --git a/cipher/rsa-common.c b/cipher/rsa-common.c index 7b562371..29b7bc81 100644 --- a/cipher/rsa-common.c +++ b/cipher/rsa-common.c @@ -1,1038 +1,1038 @@ /* rsa-common.c - Supporting functions for RSA * Copyright (C) 2011 Free Software Foundation, Inc. * Copyright (C) 2013 g10 Code GmbH * * 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 . */ #include #include #include #include #include "g10lib.h" #include "mpi.h" #include "cipher.h" #include "pubkey-internal.h" /* Turn VALUE into an octet string and store it in an allocated buffer at R_FRAME or - if R_RAME is NULL - copy it into the caller provided buffer SPACE; either SPACE or R_FRAME may be used. If SPACE if not NULL, the caller must provide a buffer of at least NBYTES. If the resulting octet string is shorter than NBYTES pad it to the left with zeroes. If VALUE does not fit into NBYTES return an error code. */ static gpg_err_code_t octet_string_from_mpi (unsigned char **r_frame, void *space, gcry_mpi_t value, size_t nbytes) { return _gcry_mpi_to_octet_string (r_frame, space, value, nbytes); } /* Encode {VALUE,VALUELEN} for an NBITS keys using the pkcs#1 block type 2 padding. On success the result is stored as a new MPI at R_RESULT. On error the value at R_RESULT is undefined. If {RANDOM_OVERRIDE, RANDOM_OVERRIDE_LEN} is given it is used as the seed instead of using a random string for it. This feature is only useful for regression tests. Note that this value may not contain zero bytes. We encode the value in this way: 0 2 RND(n bytes) 0 VALUE 0 is a marker we unfortunately can't encode because we return an MPI which strips all leading zeroes. 2 is the block type. RND are non-zero random bytes. (Note that OpenPGP includes the cipher algorithm and a checksum in VALUE; the caller needs to prepare the value accordingly.) */ gpg_err_code_t _gcry_rsa_pkcs1_encode_for_enc (gcry_mpi_t *r_result, unsigned int nbits, const unsigned char *value, size_t valuelen, const unsigned char *random_override, size_t random_override_len) { gcry_err_code_t rc = 0; unsigned char *frame = NULL; size_t nframe = (nbits+7) / 8; int i; size_t n; unsigned char *p; if (valuelen + 7 > nframe || !nframe) { /* Can't encode a VALUELEN value in a NFRAME bytes frame. */ return GPG_ERR_TOO_SHORT; /* The key is too short. */ } if ( !(frame = xtrymalloc_secure (nframe))) return gpg_err_code_from_syserror (); n = 0; frame[n++] = 0; frame[n++] = 2; /* block type */ i = nframe - 3 - valuelen; gcry_assert (i > 0); if (random_override) { int j; if (random_override_len != i) { xfree (frame); return GPG_ERR_INV_ARG; } /* Check that random does not include a zero byte. */ for (j=0; j < random_override_len; j++) if (!random_override[j]) { xfree (frame); return GPG_ERR_INV_ARG; } memcpy (frame + n, random_override, random_override_len); n += random_override_len; } else { p = _gcry_random_bytes_secure (i, GCRY_STRONG_RANDOM); /* Replace zero bytes by new values. */ for (;;) { int j, k; unsigned char *pp; /* Count the zero bytes. */ for (j=k=0; j < i; j++) { if (!p[j]) k++; } if (!k) break; /* Okay: no (more) zero bytes. */ k += k/128 + 3; /* Better get some more. */ pp = _gcry_random_bytes_secure (k, GCRY_STRONG_RANDOM); for (j=0; j < i && k; ) { if (!p[j]) p[j] = pp[--k]; if (p[j]) j++; } xfree (pp); } memcpy (frame+n, p, i); n += i; xfree (p); } frame[n++] = 0; memcpy (frame+n, value, valuelen); n += valuelen; gcry_assert (n == nframe); rc = _gcry_mpi_scan (r_result, GCRYMPI_FMT_USG, frame, n, &nframe); if (!rc &&DBG_CIPHER) log_mpidump ("PKCS#1 block type 2 encoded data", *r_result); xfree (frame); return rc; } /* Decode a plaintext in VALUE assuming pkcs#1 block type 2 padding. NBITS is the size of the secret key. On success the result is stored as a newly allocated buffer at R_RESULT and its valid length at R_RESULTLEN. On error NULL is stored at R_RESULT. */ gpg_err_code_t _gcry_rsa_pkcs1_decode_for_enc (unsigned char **r_result, size_t *r_resultlen, unsigned int nbits, gcry_mpi_t value) { gcry_error_t err; unsigned char *frame = NULL; size_t nframe = (nbits+7) / 8; size_t n; *r_result = NULL; if ( !(frame = xtrymalloc_secure (nframe))) return gpg_err_code_from_syserror (); err = _gcry_mpi_print (GCRYMPI_FMT_USG, frame, nframe, &n, value); if (err) { xfree (frame); return gcry_err_code (err); } nframe = n; /* Set NFRAME to the actual length. */ /* FRAME = 0x00 || 0x02 || PS || 0x00 || M pkcs#1 requires that the first byte is zero. Our MPIs usually strip leading zero bytes; thus we are not able to detect them. However due to the way gcry_mpi_print is implemented we may see leading zero bytes nevertheless. We handle this by making the first zero byte optional. */ if (nframe < 4) { xfree (frame); return GPG_ERR_ENCODING_PROBLEM; /* Too short. */ } n = 0; if (!frame[0]) n++; if (frame[n++] != 0x02) { xfree (frame); return GPG_ERR_ENCODING_PROBLEM; /* Wrong block type. */ } /* Skip the non-zero random bytes and the terminating zero byte. */ for (; n < nframe && frame[n] != 0x00; n++) ; if (n+1 >= nframe) { xfree (frame); return GPG_ERR_ENCODING_PROBLEM; /* No zero byte. */ } n++; /* Skip the zero byte. */ /* To avoid an extra allocation we reuse the frame buffer. The only caller of this function will anyway free the result soon. */ memmove (frame, frame + n, nframe - n); *r_result = frame; *r_resultlen = nframe - n; if (DBG_CIPHER) log_printhex ("value extracted from PKCS#1 block type 2 encoded data", *r_result, *r_resultlen); return 0; } -/* Encode {VALUE,VALUELEN} for an NBITS keys and hash algorith ALGO +/* Encode {VALUE,VALUELEN} for an NBITS keys and hash algorithm ALGO using the pkcs#1 block type 1 padding. On success the result is stored as a new MPI at R_RESULT. On error the value at R_RESULT is undefined. We encode the value in this way: 0 1 PAD(n bytes) 0 ASN(asnlen bytes) VALUE(valuelen bytes) 0 is a marker we unfortunately can't encode because we return an MPI which strips all leading zeroes. 1 is the block type. PAD consists of 0xff bytes. 0 marks the end of the padding. ASN is the DER encoding of the hash algorithm; along with the VALUE it yields a valid DER encoding. (Note that PGP prior to version 2.3 encoded the message digest as: 0 1 MD(16 bytes) 0 PAD(n bytes) 1 The MD is always 16 bytes here because it's always MD5. GnuPG does not not support pre-v2.3 signatures, but I'm including this comment so the information is easily found if needed.) */ gpg_err_code_t _gcry_rsa_pkcs1_encode_for_sig (gcry_mpi_t *r_result, unsigned int nbits, const unsigned char *value, size_t valuelen, int algo) { gcry_err_code_t rc = 0; byte asn[100]; byte *frame = NULL; size_t nframe = (nbits+7) / 8; int i; size_t n; size_t asnlen, dlen; asnlen = DIM(asn); dlen = _gcry_md_get_algo_dlen (algo); if (_gcry_md_algo_info (algo, GCRYCTL_GET_ASNOID, asn, &asnlen)) { /* We don't have yet all of the above algorithms. */ return GPG_ERR_NOT_IMPLEMENTED; } if ( valuelen != dlen ) { /* Hash value does not match the length of digest for the given algorithm. */ return GPG_ERR_CONFLICT; } if ( !dlen || dlen + asnlen + 4 > nframe) { /* Can't encode an DLEN byte digest MD into an NFRAME byte frame. */ return GPG_ERR_TOO_SHORT; } if ( !(frame = xtrymalloc (nframe)) ) return gpg_err_code_from_syserror (); /* Assemble the pkcs#1 block type 1. */ n = 0; frame[n++] = 0; frame[n++] = 1; /* block type */ i = nframe - valuelen - asnlen - 3 ; gcry_assert (i > 1); memset (frame+n, 0xff, i ); n += i; frame[n++] = 0; memcpy (frame+n, asn, asnlen); n += asnlen; memcpy (frame+n, value, valuelen ); n += valuelen; gcry_assert (n == nframe); /* Convert it into an MPI. */ rc = _gcry_mpi_scan (r_result, GCRYMPI_FMT_USG, frame, n, &nframe); if (!rc && DBG_CIPHER) log_mpidump ("PKCS#1 block type 1 encoded data", *r_result); xfree (frame); return rc; } /* Encode {VALUE,VALUELEN} for an NBITS keys using the pkcs#1 block type 1 padding. On success the result is stored as a new MPI at R_RESULT. On error the value at R_RESULT is undefined. We encode the value in this way: 0 1 PAD(n bytes) 0 VALUE(valuelen bytes) 0 is a marker we unfortunately can't encode because we return an MPI which strips all leading zeroes. 1 is the block type. PAD consists of 0xff bytes. 0 marks the end of the padding. (Note that PGP prior to version 2.3 encoded the message digest as: 0 1 MD(16 bytes) 0 PAD(n bytes) 1 The MD is always 16 bytes here because it's always MD5. GnuPG does not not support pre-v2.3 signatures, but I'm including this comment so the information is easily found if needed.) */ gpg_err_code_t _gcry_rsa_pkcs1_encode_raw_for_sig (gcry_mpi_t *r_result, unsigned int nbits, const unsigned char *value, size_t valuelen) { gcry_err_code_t rc = 0; gcry_error_t err; byte *frame = NULL; size_t nframe = (nbits+7) / 8; int i; size_t n; if ( !valuelen || valuelen + 4 > nframe) { /* Can't encode an DLEN byte digest MD into an NFRAME byte frame. */ return GPG_ERR_TOO_SHORT; } if ( !(frame = xtrymalloc (nframe)) ) return gpg_err_code_from_syserror (); /* Assemble the pkcs#1 block type 1. */ n = 0; frame[n++] = 0; frame[n++] = 1; /* block type */ i = nframe - valuelen - 3 ; gcry_assert (i > 1); memset (frame+n, 0xff, i ); n += i; frame[n++] = 0; memcpy (frame+n, value, valuelen ); n += valuelen; gcry_assert (n == nframe); /* Convert it into an MPI. */ err = _gcry_mpi_scan (r_result, GCRYMPI_FMT_USG, frame, n, &nframe); if (err) rc = gcry_err_code (err); else if (DBG_CIPHER) log_mpidump ("PKCS#1 block type 1 encoded data", *r_result); xfree (frame); return rc; } /* Mask generation function for OAEP. See RFC-3447 B.2.1. */ static gcry_err_code_t mgf1 (unsigned char *output, size_t outlen, unsigned char *seed, size_t seedlen, int algo) { size_t dlen, nbytes, n; int idx; gcry_md_hd_t hd; gcry_err_code_t err; err = _gcry_md_open (&hd, algo, 0); if (err) return err; dlen = _gcry_md_get_algo_dlen (algo); /* We skip step 1 which would be assert(OUTLEN <= 2^32). The loop in step 3 is merged with step 4 by concatenating no more octets than what would fit into OUTPUT. The ceiling for the counter IDX is implemented indirectly. */ nbytes = 0; /* Step 2. */ idx = 0; while ( nbytes < outlen ) { unsigned char c[4], *digest; if (idx) _gcry_md_reset (hd); c[0] = (idx >> 24) & 0xFF; c[1] = (idx >> 16) & 0xFF; c[2] = (idx >> 8) & 0xFF; c[3] = idx & 0xFF; idx++; _gcry_md_write (hd, seed, seedlen); _gcry_md_write (hd, c, 4); digest = _gcry_md_read (hd, 0); n = (outlen - nbytes < dlen)? (outlen - nbytes) : dlen; memcpy (output+nbytes, digest, n); nbytes += n; } _gcry_md_close (hd); return GPG_ERR_NO_ERROR; } /* RFC-3447 (pkcs#1 v2.1) OAEP encoding. NBITS is the length of the key measured in bits. ALGO is the hash function; it must be a valid and usable algorithm. {VALUE,VALUELEN} is the message to encrypt. {LABEL,LABELLEN} is the optional label to be associated with the message, if LABEL is NULL the default is to use the empty string as label. On success the encoded ciphertext is returned at R_RESULT. If {RANDOM_OVERRIDE, RANDOM_OVERRIDE_LEN} is given it is used as the seed instead of using a random string for it. This feature is only useful for regression tests. Here is figure 1 from the RFC depicting the process: +----------+---------+-------+ DB = | lHash | PS | M | +----------+---------+-------+ | +----------+ V | seed |--> MGF ---> xor +----------+ | | | +--+ V | |00| xor <----- MGF <-----| +--+ | | | | | V V V +--+----------+----------------------------+ EM = |00|maskedSeed| maskedDB | +--+----------+----------------------------+ */ gpg_err_code_t _gcry_rsa_oaep_encode (gcry_mpi_t *r_result, unsigned int nbits, int algo, const unsigned char *value, size_t valuelen, const unsigned char *label, size_t labellen, const void *random_override, size_t random_override_len) { gcry_err_code_t rc = 0; unsigned char *frame = NULL; size_t nframe = (nbits+7) / 8; unsigned char *p; size_t hlen; size_t n; *r_result = NULL; /* Set defaults for LABEL. */ if (!label || !labellen) { label = (const unsigned char*)""; labellen = 0; } hlen = _gcry_md_get_algo_dlen (algo); /* We skip step 1a which would be to check that LABELLEN is not greater than 2^61-1. See rfc-3447 7.1.1. */ /* Step 1b. Note that the obsolete rfc-2437 uses the check: valuelen > nframe - 2 * hlen - 1 . */ if (valuelen > nframe - 2 * hlen - 2 || !nframe) { /* Can't encode a VALUELEN value in a NFRAME bytes frame. */ return GPG_ERR_TOO_SHORT; /* The key is too short. */ } /* Allocate the frame. */ frame = xtrycalloc_secure (1, nframe); if (!frame) return gpg_err_code_from_syserror (); /* Step 2a: Compute the hash of the label. We store it in the frame where later the maskedDB will commence. */ _gcry_md_hash_buffer (algo, frame + 1 + hlen, label, labellen); /* Step 2b: Set octet string to zero. */ /* This has already been done while allocating FRAME. */ /* Step 2c: Create DB by concatenating lHash, PS, 0x01 and M. */ n = nframe - valuelen - 1; frame[n] = 0x01; memcpy (frame + n + 1, value, valuelen); /* Step 3d: Generate seed. We store it where the maskedSeed will go later. */ if (random_override) { if (random_override_len != hlen) { xfree (frame); return GPG_ERR_INV_ARG; } memcpy (frame + 1, random_override, hlen); } else _gcry_randomize (frame + 1, hlen, GCRY_STRONG_RANDOM); /* Step 2e and 2f: Create maskedDB. */ { unsigned char *dmask; dmask = xtrymalloc_secure (nframe - hlen - 1); if (!dmask) { rc = gpg_err_code_from_syserror (); xfree (frame); return rc; } rc = mgf1 (dmask, nframe - hlen - 1, frame+1, hlen, algo); if (rc) { xfree (dmask); xfree (frame); return rc; } for (n = 1 + hlen, p = dmask; n < nframe; n++) frame[n] ^= *p++; xfree (dmask); } /* Step 2g and 2h: Create maskedSeed. */ { unsigned char *smask; smask = xtrymalloc_secure (hlen); if (!smask) { rc = gpg_err_code_from_syserror (); xfree (frame); return rc; } rc = mgf1 (smask, hlen, frame + 1 + hlen, nframe - hlen - 1, algo); if (rc) { xfree (smask); xfree (frame); return rc; } for (n = 1, p = smask; n < 1 + hlen; n++) frame[n] ^= *p++; xfree (smask); } /* Step 2i: Concatenate 0x00, maskedSeed and maskedDB. */ /* This has already been done by using in-place operations. */ /* Convert the stuff into an MPI as expected by the caller. */ rc = _gcry_mpi_scan (r_result, GCRYMPI_FMT_USG, frame, nframe, NULL); if (!rc && DBG_CIPHER) log_mpidump ("OAEP encoded data", *r_result); xfree (frame); return rc; } /* RFC-3447 (pkcs#1 v2.1) OAEP decoding. NBITS is the length of the key measured in bits. ALGO is the hash function; it must be a valid and usable algorithm. VALUE is the raw decrypted message {LABEL,LABELLEN} is the optional label to be associated with the message, if LABEL is NULL the default is to use the empty string as label. On success the plaintext is returned as a newly allocated buffer at R_RESULT; its valid length is stored at R_RESULTLEN. On error NULL is stored at R_RESULT. */ gpg_err_code_t _gcry_rsa_oaep_decode (unsigned char **r_result, size_t *r_resultlen, unsigned int nbits, int algo, gcry_mpi_t value, const unsigned char *label, size_t labellen) { gcry_err_code_t rc; unsigned char *frame = NULL; /* Encoded messages (EM). */ unsigned char *masked_seed; /* Points into FRAME. */ unsigned char *masked_db; /* Points into FRAME. */ unsigned char *seed = NULL; /* Allocated space for the seed and DB. */ unsigned char *db; /* Points into SEED. */ unsigned char *lhash = NULL; /* Hash of the label. */ size_t nframe; /* Length of the ciphertext (EM). */ size_t hlen; /* Length of the hash digest. */ size_t db_len; /* Length of DB and masked_db. */ size_t nkey = (nbits+7)/8; /* Length of the key in bytes. */ int failed = 0; /* Error indicator. */ size_t n; *r_result = NULL; /* This code is implemented as described by rfc-3447 7.1.2. */ /* Set defaults for LABEL. */ if (!label || !labellen) { label = (const unsigned char*)""; labellen = 0; } /* Get the length of the digest. */ hlen = _gcry_md_get_algo_dlen (algo); /* Hash the label right away. */ lhash = xtrymalloc (hlen); if (!lhash) return gpg_err_code_from_syserror (); _gcry_md_hash_buffer (algo, lhash, label, labellen); /* Turn the MPI into an octet string. If the octet string is shorter than the key we pad it to the left with zeroes. This may happen due to the leading zero in OAEP frames and due to the following random octets (seed^mask) which may have leading zero bytes. This all is needed to cope with our leading zeroes suppressing MPI implementation. The code implictly implements Step 1b (bail out if NFRAME != N). */ rc = octet_string_from_mpi (&frame, NULL, value, nkey); if (rc) { xfree (lhash); return GPG_ERR_ENCODING_PROBLEM; } nframe = nkey; /* Step 1c: Check that the key is long enough. */ if ( nframe < 2 * hlen + 2 ) { xfree (frame); xfree (lhash); return GPG_ERR_ENCODING_PROBLEM; } /* Step 2 has already been done by the caller and the gcry_mpi_aprint above. */ /* Allocate space for SEED and DB. */ seed = xtrymalloc_secure (nframe - 1); if (!seed) { rc = gpg_err_code_from_syserror (); xfree (frame); xfree (lhash); return rc; } db = seed + hlen; /* To avoid chosen ciphertext attacks from now on we make sure to run all code even in the error case; this avoids possible timing attacks as described by Manger. */ /* Step 3a: Hash the label. */ /* This has already been done. */ /* Step 3b: Separate the encoded message. */ masked_seed = frame + 1; masked_db = frame + 1 + hlen; db_len = nframe - 1 - hlen; /* Step 3c and 3d: seed = maskedSeed ^ mgf(maskedDB, hlen). */ if (mgf1 (seed, hlen, masked_db, db_len, algo)) failed = 1; for (n = 0; n < hlen; n++) seed[n] ^= masked_seed[n]; /* Step 3e and 3f: db = maskedDB ^ mgf(seed, db_len). */ if (mgf1 (db, db_len, seed, hlen, algo)) failed = 1; for (n = 0; n < db_len; n++) db[n] ^= masked_db[n]; /* Step 3g: Check lhash, an possible empty padding string terminated by 0x01 and the first byte of EM being 0. */ if (memcmp (lhash, db, hlen)) failed = 1; for (n = hlen; n < db_len; n++) if (db[n] == 0x01) break; if (n == db_len) failed = 1; if (frame[0]) failed = 1; xfree (lhash); xfree (frame); if (failed) { xfree (seed); return GPG_ERR_ENCODING_PROBLEM; } /* Step 4: Output M. */ /* To avoid an extra allocation we reuse the seed buffer. The only caller of this function will anyway free the result soon. */ n++; memmove (seed, db + n, db_len - n); *r_result = seed; *r_resultlen = db_len - n; seed = NULL; if (DBG_CIPHER) log_printhex ("value extracted from OAEP encoded data", *r_result, *r_resultlen); return 0; } /* RFC-3447 (pkcs#1 v2.1) PSS encoding. Encode {VALUE,VALUELEN} for an NBITS key. Note that VALUE is already the mHash from the picture below. ALGO is a valid hash algorithm and SALTLEN is the length of salt to be used. On success the result is stored as a new MPI at R_RESULT. On error the value at R_RESULT is undefined. If {RANDOM_OVERRIDE, RANDOM_OVERRIDE_LEN} is given it is used as the salt instead of using a random string for the salt. This feature is only useful for regression tests. Here is figure 2 from the RFC (errata 595 applied) depicting the process: +-----------+ | M | +-----------+ | V Hash | V +--------+----------+----------+ M' = |Padding1| mHash | salt | +--------+----------+----------+ | +--------+----------+ V DB = |Padding2| salt | Hash +--------+----------+ | | | V | +----+ xor <--- MGF <---| |0xbc| | | +----+ | | | V V V +-------------------+----------+----+ EM = | maskedDB | H |0xbc| +-------------------+----------+----+ */ gpg_err_code_t _gcry_rsa_pss_encode (gcry_mpi_t *r_result, unsigned int nbits, int algo, const unsigned char *value, size_t valuelen, int saltlen, const void *random_override, size_t random_override_len) { gcry_err_code_t rc = 0; size_t hlen; /* Length of the hash digest. */ unsigned char *em = NULL; /* Encoded message. */ size_t emlen = (nbits+7)/8; /* Length in bytes of EM. */ unsigned char *h; /* Points into EM. */ unsigned char *buf = NULL; /* Help buffer. */ size_t buflen; /* Length of BUF. */ unsigned char *mhash; /* Points into BUF. */ unsigned char *salt; /* Points into BUF. */ unsigned char *dbmask; /* Points into BUF. */ unsigned char *p; size_t n; /* This code is implemented as described by rfc-3447 9.1.1. */ /* Get the length of the digest. */ hlen = _gcry_md_get_algo_dlen (algo); gcry_assert (hlen); /* We expect a valid ALGO here. */ /* Allocate a help buffer and setup some pointers. */ buflen = 8 + hlen + saltlen + (emlen - hlen - 1); buf = xtrymalloc (buflen); if (!buf) { rc = gpg_err_code_from_syserror (); goto leave; } mhash = buf + 8; salt = mhash + hlen; dbmask= salt + saltlen; /* Step 2: That would be: mHash = Hash(M) but our input is already mHash thus we do only a consistency check and copy to MHASH. */ if (valuelen != hlen) { rc = GPG_ERR_INV_LENGTH; goto leave; } memcpy (mhash, value, hlen); /* Step 3: Check length constraints. */ if (emlen < hlen + saltlen + 2) { rc = GPG_ERR_TOO_SHORT; goto leave; } /* Allocate space for EM. */ em = xtrymalloc (emlen); if (!em) { rc = gpg_err_code_from_syserror (); goto leave; } h = em + emlen - 1 - hlen; /* Step 4: Create a salt. */ if (saltlen) { if (random_override) { if (random_override_len != saltlen) { rc = GPG_ERR_INV_ARG; goto leave; } memcpy (salt, random_override, saltlen); } else _gcry_randomize (salt, saltlen, GCRY_STRONG_RANDOM); } /* Step 5 and 6: M' = Hash(Padding1 || mHash || salt). */ memset (buf, 0, 8); /* Padding. */ _gcry_md_hash_buffer (algo, h, buf, 8 + hlen + saltlen); /* Step 7 and 8: DB = PS || 0x01 || salt. */ /* Note that we use EM to store DB and later Xor in-place. */ p = em + emlen - 1 - hlen - saltlen - 1; memset (em, 0, p - em); *p++ = 0x01; memcpy (p, salt, saltlen); /* Step 9: dbmask = MGF(H, emlen - hlen - 1). */ mgf1 (dbmask, emlen - hlen - 1, h, hlen, algo); /* Step 10: maskedDB = DB ^ dbMask */ for (n = 0, p = dbmask; n < emlen - hlen - 1; n++, p++) em[n] ^= *p; /* Step 11: Set the leftmost bits to zero. */ em[0] &= 0xFF >> (8 * emlen - nbits); /* Step 12: EM = maskedDB || H || 0xbc. */ em[emlen-1] = 0xbc; /* Convert EM into an MPI. */ rc = _gcry_mpi_scan (r_result, GCRYMPI_FMT_USG, em, emlen, NULL); if (!rc && DBG_CIPHER) log_mpidump ("PSS encoded data", *r_result); leave: if (em) { wipememory (em, emlen); xfree (em); } if (buf) { wipememory (buf, buflen); xfree (buf); } return rc; } /* Verify a signature assuming PSS padding. VALUE is the hash of the message (mHash) encoded as an MPI; its length must match the digest length of ALGO. ENCODED is the output of the RSA public key function (EM). NBITS is the size of the public key. ALGO is the hash algorithm and SALTLEN is the length of the used salt. The function returns 0 on success or on error code. */ gpg_err_code_t _gcry_rsa_pss_verify (gcry_mpi_t value, gcry_mpi_t encoded, unsigned int nbits, int algo, size_t saltlen) { gcry_err_code_t rc = 0; size_t hlen; /* Length of the hash digest. */ unsigned char *em = NULL; /* Encoded message. */ size_t emlen = (nbits+7)/8; /* Length in bytes of EM. */ unsigned char *salt; /* Points into EM. */ unsigned char *h; /* Points into EM. */ unsigned char *buf = NULL; /* Help buffer. */ size_t buflen; /* Length of BUF. */ unsigned char *dbmask; /* Points into BUF. */ unsigned char *mhash; /* Points into BUF. */ unsigned char *p; size_t n; /* This code is implemented as described by rfc-3447 9.1.2. */ /* Get the length of the digest. */ hlen = _gcry_md_get_algo_dlen (algo); gcry_assert (hlen); /* We expect a valid ALGO here. */ /* Allocate a help buffer and setup some pointers. This buffer is used for two purposes: +------------------------------+-------+ 1. | dbmask | mHash | +------------------------------+-------+ emlen - hlen - 1 hlen +----------+-------+---------+-+-------+ 2. | padding1 | mHash | salt | | mHash | +----------+-------+---------+-+-------+ 8 hlen saltlen hlen */ buflen = 8 + hlen + saltlen; if (buflen < emlen - hlen - 1) buflen = emlen - hlen - 1; buflen += hlen; buf = xtrymalloc (buflen); if (!buf) { rc = gpg_err_code_from_syserror (); goto leave; } dbmask = buf; mhash = buf + buflen - hlen; /* Step 2: That would be: mHash = Hash(M) but our input is already mHash thus we only need to convert VALUE into MHASH. */ rc = octet_string_from_mpi (NULL, mhash, value, hlen); if (rc) goto leave; /* Convert the signature into an octet string. */ rc = octet_string_from_mpi (&em, NULL, encoded, emlen); if (rc) goto leave; /* Step 3: Check length of EM. Because we internally use MPI functions we can't do this properly; EMLEN is always the length of the key because octet_string_from_mpi needs to left pad the result with zero to cope with the fact that our MPIs suppress all leading zeroes. Thus what we test here are merely the digest and salt lengths to the key. */ if (emlen < hlen + saltlen + 2) { rc = GPG_ERR_TOO_SHORT; /* For the hash and saltlen. */ goto leave; } /* Step 4: Check last octet. */ if (em[emlen - 1] != 0xbc) { rc = GPG_ERR_BAD_SIGNATURE; goto leave; } /* Step 5: Split EM. */ h = em + emlen - 1 - hlen; /* Step 6: Check the leftmost bits. */ if ((em[0] & ~(0xFF >> (8 * emlen - nbits)))) { rc = GPG_ERR_BAD_SIGNATURE; goto leave; } /* Step 7: dbmask = MGF(H, emlen - hlen - 1). */ mgf1 (dbmask, emlen - hlen - 1, h, hlen, algo); /* Step 8: maskedDB = DB ^ dbMask. */ for (n = 0, p = dbmask; n < emlen - hlen - 1; n++, p++) em[n] ^= *p; /* Step 9: Set leftmost bits in DB to zero. */ em[0] &= 0xFF >> (8 * emlen - nbits); /* Step 10: Check the padding of DB. */ for (n = 0; n < emlen - hlen - saltlen - 2 && !em[n]; n++) ; if (n != emlen - hlen - saltlen - 2 || em[n++] != 1) { rc = GPG_ERR_BAD_SIGNATURE; goto leave; } /* Step 11: Extract salt from DB. */ salt = em + n; /* Step 12: M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt */ memset (buf, 0, 8); memcpy (buf+8, mhash, hlen); memcpy (buf+8+hlen, salt, saltlen); /* Step 13: H' = Hash(M'). */ _gcry_md_hash_buffer (algo, buf, buf, 8 + hlen + saltlen); /* Step 14: Check H == H'. */ rc = memcmp (h, buf, hlen) ? GPG_ERR_BAD_SIGNATURE : GPG_ERR_NO_ERROR; leave: if (em) { wipememory (em, emlen); xfree (em); } if (buf) { wipememory (buf, buflen); xfree (buf); } return rc; } diff --git a/cipher/rsa.c b/cipher/rsa.c index b6c73741..895ee04c 100644 --- a/cipher/rsa.c +++ b/cipher/rsa.c @@ -1,1990 +1,1990 @@ /* 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 . */ /* 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 #include #include #include #include #include "g10lib.h" #include "mpi.h" #include "cipher.h" #include "pubkey-internal.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; static const char *rsa_names[] = { "rsa", "openpgp-rsa", "oid.1.2.840.113549.1.1.1", NULL, }; /* A sample 2048 bit RSA key used for the selftests. */ static const char sample_secret_key[] = " (private-key" " (rsa" " (n #009F56231A3D82E3E7D613D59D53E9AB921BEF9F08A782AED0B6E46ADBC853EC" " 7C71C422435A3CD8FA0DB9EFD55CD3295BADC4E8E2E2B94E15AE82866AB8ADE8" " 7E469FAE76DC3577DE87F1F419C4EB41123DFAF8D16922D5EDBAD6E9076D5A1C" " 958106F0AE5E2E9193C6B49124C64C2A241C4075D4AF16299EB87A6585BAE917" " DEF27FCDD165764D069BC18D16527B29DAAB549F7BBED4A7C6A842D203ED6613" " 6E2411744E432CD26D940132F25874483DCAEECDFD95744819CBCF1EA810681C" " 42907EBCB1C7EAFBE75C87EC32C5413EA10476545D3FC7B2ADB1B66B7F200918" " 664B0E5261C2895AA28B0DE321E921B3F877172CCCAB81F43EF98002916156F6CB#)" " (e #010001#)" " (d #07EF82500C403899934FE993AC5A36F14FF2DF38CF1EF315F205EE4C83EDAA19" " 8890FC23DE9AA933CAFB37B6A8A8DBA675411958337287310D3FF2F1DDC0CB93" " 7E70F57F75F833C021852B631D2B9A520E4431A03C5C3FCB5742DCD841D9FB12" " 771AA1620DCEC3F1583426066ED9DC3F7028C5B59202C88FDF20396E2FA0EC4F" " 5A22D9008F3043673931BC14A5046D6327398327900867E39CC61B2D1AFE2F48" " EC8E1E3861C68D257D7425F4E6F99ABD77D61F10CA100EFC14389071831B33DD" " 69CC8EABEF860D1DC2AAA84ABEAE5DFC91BC124DAF0F4C8EF5BBEA436751DE84" " 3A8063E827A024466F44C28614F93B0732A100D4A0D86D532FE1E22C7725E401#)" " (p #00C29D438F115825779631CD665A5739367F3E128ADC29766483A46CA80897E0" " 79B32881860B8F9A6A04C2614A904F6F2578DAE13EA67CD60AE3D0AA00A1FF9B" " 441485E44B2DC3D0B60260FBFE073B5AC72FAF67964DE15C8212C389D20DB9CF" " 54AF6AEF5C4196EAA56495DD30CF709F499D5AB30CA35E086C2A1589D6283F1783#)" " (q #00D1984135231CB243FE959C0CBEF551EDD986AD7BEDF71EDF447BE3DA27AF46" " 79C974A6FA69E4D52FE796650623DE70622862713932AA2FD9F2EC856EAEAA77" " 88B4EA6084DC81C902F014829B18EA8B2666EC41586818E0589E18876065F97E" " 8D22CE2DA53A05951EC132DCEF41E70A9C35F4ACC268FFAC2ADF54FA1DA110B919#)" " (u #67CF0FD7635205DD80FA814EE9E9C267C17376BF3209FB5D1BC42890D2822A04" " 479DAF4D5B6ED69D0F8D1AF94164D07F8CD52ECEFE880641FA0F41DDAB1785E4" " A37A32F997A516480B4CD4F6482B9466A1765093ED95023CA32D5EDC1E34CEE9" " AF595BC51FE43C4BF810FA225AF697FB473B83815966188A4312C048B885E3F7#)))"; /* A sample 2048 bit RSA key used for the selftests (public only). */ static const char sample_public_key[] = " (public-key" " (rsa" " (n #009F56231A3D82E3E7D613D59D53E9AB921BEF9F08A782AED0B6E46ADBC853EC" " 7C71C422435A3CD8FA0DB9EFD55CD3295BADC4E8E2E2B94E15AE82866AB8ADE8" " 7E469FAE76DC3577DE87F1F419C4EB41123DFAF8D16922D5EDBAD6E9076D5A1C" " 958106F0AE5E2E9193C6B49124C64C2A241C4075D4AF16299EB87A6585BAE917" " DEF27FCDD165764D069BC18D16527B29DAAB549F7BBED4A7C6A842D203ED6613" " 6E2411744E432CD26D940132F25874483DCAEECDFD95744819CBCF1EA810681C" " 42907EBCB1C7EAFBE75C87EC32C5413EA10476545D3FC7B2ADB1B66B7F200918" " 664B0E5261C2895AA28B0DE321E921B3F877172CCCAB81F43EF98002916156F6CB#)" " (e #010001#)))"; static int test_keys (RSA_secret_key *sk, unsigned nbits); 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); static unsigned int rsa_get_nbits (gcry_sexp_t parms); /* 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 = mpi_new (nbits); gcry_mpi_t ciphertext = mpi_new (nbits); gcry_mpi_t decr_plaintext = mpi_new (nbits); gcry_mpi_t signature = 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 (!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 (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 (mpi_cmp (decr_plaintext, plaintext)) goto leave; /* Signature does not match. */ /* Modify the signature and check that the signing fails. */ mpi_add_ui (signature, signature, 1); public (decr_plaintext, signature, &pk); if (!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 = !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 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_std (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 Sphinx. */ /* 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 = 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 = mpi_snew ( nbits ); g = mpi_snew ( nbits ); f = mpi_snew ( nbits ); mpi_sub_ui( t1, p, 1 ); mpi_sub_ui( t2, q, 1 ); mpi_mul( phi, t1, t2 ); mpi_gcd (g, t1, t2); mpi_fdiv_q(f, phi, g); while (!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 = mpi_snew ( nbits ); mpi_invm (d, e, f ); /* calculate the inverse of p and q (used for chinese remainder theorem)*/ u = 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; } /**************** * 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 Use this public exponent. If the given exponent * is not odd one is internally added to it. * TESTPARMS: If set, do not generate but test whether the p,q is probably prime * Returns key with zeroes to not break code calling this function. * 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_fips (RSA_secret_key *sk, unsigned int nbits, unsigned long use_e, gcry_sexp_t testparms, 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 p1, q1; gcry_mpi_t n; /* the public key */ gcry_mpi_t e; /* the exponent */ gcry_mpi_t g; gcry_mpi_t minp; gcry_mpi_t diff, mindiff; gcry_random_level_t random_level; unsigned int pbits = nbits/2; unsigned int i; int pqswitch; gpg_err_code_t ec = GPG_ERR_NO_PRIME; if (nbits < 1024 || (nbits & 0x1FF)) return GPG_ERR_INV_VALUE; if (_gcry_enforced_fips_mode() && nbits != 2048 && nbits != 3072) 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; if (testparms) { /* Parameters to derive the key are given. */ /* Note that we explicitly need to setup the values of tbl because some compilers (e.g. OpenWatcom, IRIX) don't allow to initialize a structure with automatic variables. */ struct { const char *name; gcry_mpi_t *value; } tbl[] = { { "e" }, { "p" }, { "q" }, { NULL } }; int idx; gcry_sexp_t oneparm; tbl[0].value = &e; tbl[1].value = &p; tbl[2].value = &q; for (idx=0; tbl[idx].name; idx++) { oneparm = sexp_find_token (testparms, tbl[idx].name, 0); if (oneparm) { *tbl[idx].value = sexp_nth_mpi (oneparm, 1, GCRYMPI_FMT_USG); sexp_release (oneparm); } } for (idx=0; tbl[idx].name; idx++) if (!*tbl[idx].value) break; if (tbl[idx].name) { /* At least one parameter is missing. */ for (idx=0; tbl[idx].name; idx++) _gcry_mpi_release (*tbl[idx].value); return GPG_ERR_MISSING_VALUE; } } else { if (use_e < 65537) use_e = 65537; /* This is the smallest value allowed by FIPS */ e = mpi_alloc ((32+BITS_PER_MPI_LIMB-1)/BITS_PER_MPI_LIMB); use_e |= 1; /* make sure this is odd */ mpi_set_ui (e, use_e); p = mpi_snew (pbits); q = mpi_snew (pbits); } n = mpi_new (nbits); d = mpi_snew (nbits); u = mpi_snew (nbits); /* prepare approximate minimum p and q */ minp = mpi_new (pbits); mpi_set_ui (minp, 0xB504F334); mpi_lshift (minp, minp, pbits - 32); /* prepare minimum p and q difference */ diff = mpi_new (pbits); mindiff = mpi_new (pbits - 99); mpi_set_ui (mindiff, 1); mpi_lshift (mindiff, mindiff, pbits - 100); p1 = mpi_snew (pbits); q1 = mpi_snew (pbits); g = mpi_snew (pbits); retry: /* generate p and q */ for (i = 0; i < 5 * pbits; i++) { ploop: if (!testparms) { _gcry_mpi_randomize (p, pbits, random_level); } if (mpi_cmp (p, minp) < 0) { if (testparms) goto err; goto ploop; } mpi_sub_ui (p1, p, 1); if (mpi_gcd (g, p1, e)) { if (_gcry_fips186_4_prime_check (p, pbits) != GPG_ERR_NO_ERROR) { /* not a prime */ if (testparms) goto err; } else break; } else if (testparms) goto err; } if (i >= 5 * pbits) goto err; for (i = 0; i < 5 * pbits; i++) { qloop: if (!testparms) { _gcry_mpi_randomize (q, pbits, random_level); } if (mpi_cmp (q, minp) < 0) { if (testparms) goto err; goto qloop; } if (mpi_cmp (p, q) > 0) { pqswitch = 1; mpi_sub (diff, p, q); } else { pqswitch = 0; mpi_sub (diff, q, p); } if (mpi_cmp (diff, mindiff) < 0) { if (testparms) goto err; goto qloop; } mpi_sub_ui (q1, q, 1); if (mpi_gcd (g, q1, e)) { if (_gcry_fips186_4_prime_check (q, pbits) != GPG_ERR_NO_ERROR) { /* not a prime */ if (testparms) goto err; } else break; } else if (testparms) goto err; } if (i >= 5 * pbits) goto err; if (testparms) { mpi_clear (p); mpi_clear (q); } else { gcry_mpi_t f; if (pqswitch) { gcry_mpi_t tmp; tmp = p; p = q; q = tmp; } f = mpi_snew (nbits); /* calculate the modulus */ mpi_mul (n, p, q); /* calculate the secret key d = e^1 mod phi */ mpi_gcd (g, p1, q1); mpi_fdiv_q (f, p1, g); mpi_mul (f, f, q1); mpi_invm (d, e, f); _gcry_mpi_release (f); if (mpi_get_nbits (d) < pbits) goto retry; /* calculate the inverse of p and q (used for chinese remainder theorem)*/ mpi_invm (u, p, q ); } ec = 0; if (DBG_CIPHER) { log_mpidump(" p= ", p ); log_mpidump(" q= ", q ); log_mpidump(" n= ", n ); log_mpidump(" e= ", e ); log_mpidump(" d= ", d ); log_mpidump(" u= ", u ); } err: _gcry_mpi_release (p1); _gcry_mpi_release (q1); _gcry_mpi_release (g); _gcry_mpi_release (minp); _gcry_mpi_release (mindiff); _gcry_mpi_release (diff); 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 (ec || (!testparms && 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; if (!ec) { fips_signal_error ("self-test after key generation failed"); return GPG_ERR_SELFTEST_FAILED; } } return ec; } /* Helper for generate_x931. */ static gcry_mpi_t gen_x931_parm_xp (unsigned int nbits) { gcry_mpi_t xp; xp = mpi_snew (nbits); _gcry_mpi_randomize (xp, nbits, GCRY_VERY_STRONG_RANDOM); /* The requirement for Xp is: sqrt{2}*2^{nbits-1} <= xp <= 2^{nbits} - 1 We set the two high order bits to 1 to satisfy the lower bound. By using mpi_set_highbit we make sure that the upper bound is satisfied as well. */ mpi_set_highbit (xp, nbits-1); mpi_set_bit (xp, nbits-2); gcry_assert ( mpi_get_nbits (xp) == nbits ); return xp; } /* Helper for generate_x931. */ static gcry_mpi_t gen_x931_parm_xi (void) { gcry_mpi_t xi; xi = mpi_snew (101); _gcry_mpi_randomize (xi, 101, GCRY_VERY_STRONG_RANDOM); mpi_set_highbit (xi, 100); gcry_assert ( mpi_get_nbits (xi) == 101 ); return xi; } /* Variant of the standard key generation code using the algorithm from X9.31. Using this algorithm has the advantage that the generation can be made deterministic which is required for CAVS testing. */ static gpg_err_code_t generate_x931 (RSA_secret_key *sk, unsigned int nbits, unsigned long e_value, gcry_sexp_t deriveparms, int *swapped) { gcry_mpi_t p, q; /* The two primes. */ gcry_mpi_t e; /* The public exponent. */ gcry_mpi_t n; /* The public key. */ gcry_mpi_t d; /* The private key */ gcry_mpi_t u; /* The inverse of p and q. */ gcry_mpi_t pm1; /* p - 1 */ gcry_mpi_t qm1; /* q - 1 */ gcry_mpi_t phi; /* Euler totient. */ gcry_mpi_t f, g; /* Helper. */ *swapped = 0; if (e_value == 1) /* Alias for a secure value. */ e_value = 65537; /* Point 1 of section 4.1: k = 1024 + 256s with S >= 0 */ if (nbits < 1024 || (nbits % 256)) return GPG_ERR_INV_VALUE; /* Point 2: 2 <= bitlength(e) < 2^{k-2} Note that we do not need to check the upper bound because we use an unsigned long for E and thus there is no way for E to reach that limit. */ if (e_value < 3) return GPG_ERR_INV_VALUE; - /* Our implementaion requires E to be odd. */ + /* Our implementation requires E to be odd. */ if (!(e_value & 1)) return GPG_ERR_INV_VALUE; /* Point 3: e > 0 or e 0 if it is to be randomly generated. We support only a fixed E and thus there is no need for an extra test. */ /* Compute or extract the derive parameters. */ { gcry_mpi_t xp1 = NULL; gcry_mpi_t xp2 = NULL; gcry_mpi_t xp = NULL; gcry_mpi_t xq1 = NULL; gcry_mpi_t xq2 = NULL; gcry_mpi_t xq = NULL; gcry_mpi_t tmpval; if (!deriveparms) { /* Not given: Generate them. */ xp = gen_x931_parm_xp (nbits/2); /* Make sure that |xp - xq| > 2^{nbits - 100} holds. */ tmpval = mpi_snew (nbits/2); do { _gcry_mpi_release (xq); xq = gen_x931_parm_xp (nbits/2); mpi_sub (tmpval, xp, xq); } while (mpi_get_nbits (tmpval) <= (nbits/2 - 100)); _gcry_mpi_release (tmpval); xp1 = gen_x931_parm_xi (); xp2 = gen_x931_parm_xi (); xq1 = gen_x931_parm_xi (); xq2 = gen_x931_parm_xi (); } else { /* Parameters to derive the key are given. */ /* Note that we explicitly need to setup the values of tbl because some compilers (e.g. OpenWatcom, IRIX) don't allow to initialize a structure with automatic variables. */ struct { const char *name; gcry_mpi_t *value; } tbl[] = { { "Xp1" }, { "Xp2" }, { "Xp" }, { "Xq1" }, { "Xq2" }, { "Xq" }, { NULL } }; int idx; gcry_sexp_t oneparm; tbl[0].value = &xp1; tbl[1].value = &xp2; tbl[2].value = &xp; tbl[3].value = &xq1; tbl[4].value = &xq2; tbl[5].value = &xq; for (idx=0; tbl[idx].name; idx++) { oneparm = sexp_find_token (deriveparms, tbl[idx].name, 0); if (oneparm) { *tbl[idx].value = sexp_nth_mpi (oneparm, 1, GCRYMPI_FMT_USG); sexp_release (oneparm); } } for (idx=0; tbl[idx].name; idx++) if (!*tbl[idx].value) break; if (tbl[idx].name) { /* At least one parameter is missing. */ for (idx=0; tbl[idx].name; idx++) _gcry_mpi_release (*tbl[idx].value); return GPG_ERR_MISSING_VALUE; } } e = mpi_alloc_set_ui (e_value); /* Find two prime numbers. */ p = _gcry_derive_x931_prime (xp, xp1, xp2, e, NULL, NULL); q = _gcry_derive_x931_prime (xq, xq1, xq2, e, NULL, NULL); _gcry_mpi_release (xp); xp = NULL; _gcry_mpi_release (xp1); xp1 = NULL; _gcry_mpi_release (xp2); xp2 = NULL; _gcry_mpi_release (xq); xq = NULL; _gcry_mpi_release (xq1); xq1 = NULL; _gcry_mpi_release (xq2); xq2 = NULL; if (!p || !q) { _gcry_mpi_release (p); _gcry_mpi_release (q); _gcry_mpi_release (e); return GPG_ERR_NO_PRIME; } } /* Compute the public modulus. We make sure that p is smaller than q to allow the use of the CRT. */ if (mpi_cmp (p, q) > 0 ) { mpi_swap (p, q); *swapped = 1; } n = mpi_new (nbits); mpi_mul (n, p, q); /* Compute the Euler totient: phi = (p-1)(q-1) */ pm1 = mpi_snew (nbits/2); qm1 = mpi_snew (nbits/2); phi = mpi_snew (nbits); mpi_sub_ui (pm1, p, 1); mpi_sub_ui (qm1, q, 1); mpi_mul (phi, pm1, qm1); g = mpi_snew (nbits); gcry_assert (mpi_gcd (g, e, phi)); /* Compute: f = lcm(p-1,q-1) = phi / gcd(p-1,q-1) */ mpi_gcd (g, pm1, qm1); f = pm1; pm1 = NULL; _gcry_mpi_release (qm1); qm1 = NULL; mpi_fdiv_q (f, phi, g); _gcry_mpi_release (phi); phi = NULL; d = g; g = NULL; /* Compute the secret key: d = e^{-1} mod lcm(p-1,q-1) */ mpi_invm (d, e, f); /* Compute the inverse of p and q. */ u = f; f = NULL; mpi_invm (u, p, q ); if( DBG_CIPHER ) { if (*swapped) log_debug ("p and q are swapped\n"); log_mpidump(" p", p ); log_mpidump(" q", q ); log_mpidump(" n", n ); log_mpidump(" e", e ); log_mpidump(" d", d ); log_mpidump(" u", u ); } 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 whether 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); log_printmpi (" 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); log_printmpi (" 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 ) { /* Remove superfluous leading zeroes from INPUT. */ mpi_normalize (input); 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_has_sign ( h ) ) mpi_add ( h, h, skey->q ); mpi_mulm( h, skey->u, h, skey->q ); /* m = m1 + h * p */ mpi_mul ( h, h, skey->p ); mpi_add ( output, m1, h ); mpi_free ( h ); mpi_free ( m1 ); mpi_free ( m2 ); } } static void secret_blinded (gcry_mpi_t output, gcry_mpi_t input, RSA_secret_key *sk, unsigned int nbits) { gcry_mpi_t r; /* Random number needed for blinding. */ gcry_mpi_t ri; /* Modular multiplicative inverse of r. */ gcry_mpi_t bldata; /* Blinded data to decrypt. */ /* 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). The random * number needs to be only unpredictable, thus we employ the * gcry_create_nonce function by using GCRY_WEAK_RANDOM with * gcry_mpi_randomize. */ r = mpi_snew (nbits); ri = mpi_snew (nbits); bldata = mpi_snew (nbits); do { _gcry_mpi_randomize (r, nbits, GCRY_WEAK_RANDOM); mpi_mod (r, r, sk->n); } while (!mpi_invm (ri, r, sk->n)); /* Do blinding. We calculate: y = (x * r^e) mod n, where r is the * random number, e is the public exponent, x is the non-blinded * input data and n is the RSA modulus. */ mpi_powm (bldata, r, sk->e, sk->n); mpi_mulm (bldata, bldata, input, sk->n); /* Perform decryption. */ secret (output, bldata, sk); _gcry_mpi_release (bldata); /* Undo blinding. 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. */ mpi_mulm (output, output, ri, sk->n); _gcry_mpi_release (r); _gcry_mpi_release (ri); } /********************************************* ************** interface ****************** *********************************************/ static gcry_err_code_t rsa_generate (const gcry_sexp_t genparms, gcry_sexp_t *r_skey) { gpg_err_code_t ec; unsigned int nbits; unsigned long evalue; RSA_secret_key sk; gcry_sexp_t deriveparms; int flags = 0; gcry_sexp_t l1; gcry_sexp_t swap_info = NULL; memset (&sk, 0, sizeof sk); ec = _gcry_pk_util_get_nbits (genparms, &nbits); if (ec) return ec; ec = _gcry_pk_util_get_rsa_use_e (genparms, &evalue); if (ec) return ec; /* Parse the optional flags list. */ l1 = sexp_find_token (genparms, "flags", 0); if (l1) { ec = _gcry_pk_util_parse_flaglist (l1, &flags, NULL); sexp_release (l1); if (ec) return ec; } deriveparms = (genparms? sexp_find_token (genparms, "derive-parms", 0) : NULL); if (!deriveparms) { /* Parse the optional "use-x931" flag. */ l1 = sexp_find_token (genparms, "use-x931", 0); if (l1) { flags |= PUBKEY_FLAG_USE_X931; sexp_release (l1); } } if (deriveparms || (flags & PUBKEY_FLAG_USE_X931)) { int swapped; ec = generate_x931 (&sk, nbits, evalue, deriveparms, &swapped); sexp_release (deriveparms); if (!ec && swapped) ec = sexp_new (&swap_info, "(misc-key-info(p-q-swapped))", 0, 1); } else { /* Parse the optional "transient-key" flag. */ if (!(flags & PUBKEY_FLAG_TRANSIENT_KEY)) { l1 = sexp_find_token (genparms, "transient-key", 0); if (l1) { flags |= PUBKEY_FLAG_TRANSIENT_KEY; sexp_release (l1); } } deriveparms = (genparms? sexp_find_token (genparms, "test-parms", 0) /**/ : NULL); /* Generate. */ if (deriveparms || fips_mode()) { ec = generate_fips (&sk, nbits, evalue, deriveparms, !!(flags & PUBKEY_FLAG_TRANSIENT_KEY)); } else { ec = generate_std (&sk, nbits, evalue, !!(flags & PUBKEY_FLAG_TRANSIENT_KEY)); } sexp_release (deriveparms); } if (!ec) { ec = sexp_build (r_skey, NULL, "(key-data" " (public-key" " (rsa(n%m)(e%m)))" " (private-key" " (rsa(n%m)(e%m)(d%m)(p%m)(q%m)(u%m)))" " %S)", sk.n, sk.e, sk.n, sk.e, sk.d, sk.p, sk.q, sk.u, swap_info); } mpi_free (sk.n); mpi_free (sk.e); mpi_free (sk.p); mpi_free (sk.q); mpi_free (sk.d); mpi_free (sk.u); sexp_release (swap_info); return ec; } static gcry_err_code_t rsa_check_secret_key (gcry_sexp_t keyparms) { gcry_err_code_t rc; RSA_secret_key sk = {NULL, NULL, NULL, NULL, NULL, NULL}; /* To check the key we need the optional parameters. */ rc = sexp_extract_param (keyparms, NULL, "nedpqu", &sk.n, &sk.e, &sk.d, &sk.p, &sk.q, &sk.u, NULL); if (rc) goto leave; if (!check_secret_key (&sk)) rc = GPG_ERR_BAD_SECKEY; leave: _gcry_mpi_release (sk.n); _gcry_mpi_release (sk.e); _gcry_mpi_release (sk.d); _gcry_mpi_release (sk.p); _gcry_mpi_release (sk.q); _gcry_mpi_release (sk.u); if (DBG_CIPHER) log_debug ("rsa_testkey => %s\n", gpg_strerror (rc)); return rc; } static gcry_err_code_t rsa_encrypt (gcry_sexp_t *r_ciph, gcry_sexp_t s_data, gcry_sexp_t keyparms) { gcry_err_code_t rc; struct pk_encoding_ctx ctx; gcry_mpi_t data = NULL; RSA_public_key pk = {NULL, NULL}; gcry_mpi_t ciph = NULL; _gcry_pk_util_init_encoding_ctx (&ctx, PUBKEY_OP_ENCRYPT, rsa_get_nbits (keyparms)); /* Extract the data. */ rc = _gcry_pk_util_data_to_mpi (s_data, &data, &ctx); if (rc) goto leave; if (DBG_CIPHER) log_mpidump ("rsa_encrypt data", data); if (!data || mpi_is_opaque (data)) { rc = GPG_ERR_INV_DATA; goto leave; } /* Extract the key. */ rc = sexp_extract_param (keyparms, NULL, "ne", &pk.n, &pk.e, NULL); if (rc) goto leave; if (DBG_CIPHER) { log_mpidump ("rsa_encrypt n", pk.n); log_mpidump ("rsa_encrypt e", pk.e); } /* Do RSA computation and build result. */ ciph = mpi_new (0); public (ciph, data, &pk); if (DBG_CIPHER) log_mpidump ("rsa_encrypt res", ciph); if ((ctx.flags & PUBKEY_FLAG_FIXEDLEN)) { /* We need to make sure to return the correct length to avoid problems with missing leading zeroes. */ unsigned char *em; size_t emlen = (mpi_get_nbits (pk.n)+7)/8; rc = _gcry_mpi_to_octet_string (&em, NULL, ciph, emlen); if (!rc) { rc = sexp_build (r_ciph, NULL, "(enc-val(rsa(a%b)))", (int)emlen, em); xfree (em); } } else rc = sexp_build (r_ciph, NULL, "(enc-val(rsa(a%m)))", ciph); leave: _gcry_mpi_release (ciph); _gcry_mpi_release (pk.n); _gcry_mpi_release (pk.e); _gcry_mpi_release (data); _gcry_pk_util_free_encoding_ctx (&ctx); if (DBG_CIPHER) log_debug ("rsa_encrypt => %s\n", gpg_strerror (rc)); return rc; } static gcry_err_code_t rsa_decrypt (gcry_sexp_t *r_plain, gcry_sexp_t s_data, gcry_sexp_t keyparms) { gpg_err_code_t rc; struct pk_encoding_ctx ctx; gcry_sexp_t l1 = NULL; gcry_mpi_t data = NULL; RSA_secret_key sk = {NULL, NULL, NULL, NULL, NULL, NULL}; gcry_mpi_t plain = NULL; unsigned char *unpad = NULL; size_t unpadlen = 0; _gcry_pk_util_init_encoding_ctx (&ctx, PUBKEY_OP_DECRYPT, rsa_get_nbits (keyparms)); /* Extract the data. */ rc = _gcry_pk_util_preparse_encval (s_data, rsa_names, &l1, &ctx); if (rc) goto leave; rc = sexp_extract_param (l1, NULL, "a", &data, NULL); if (rc) goto leave; if (DBG_CIPHER) log_printmpi ("rsa_decrypt data", data); if (mpi_is_opaque (data)) { rc = GPG_ERR_INV_DATA; goto leave; } /* Extract the key. */ rc = sexp_extract_param (keyparms, NULL, "nedp?q?u?", &sk.n, &sk.e, &sk.d, &sk.p, &sk.q, &sk.u, NULL); if (rc) goto leave; if (DBG_CIPHER) { log_printmpi ("rsa_decrypt n", sk.n); log_printmpi ("rsa_decrypt e", sk.e); if (!fips_mode ()) { log_printmpi ("rsa_decrypt d", sk.d); log_printmpi ("rsa_decrypt p", sk.p); log_printmpi ("rsa_decrypt q", sk.q); log_printmpi ("rsa_decrypt u", sk.u); } } /* Better make sure that there are no superfluous leading zeroes in the input and it has not been "padded" using multiples of N. This mitigates side-channel attacks (CVE-2013-4576). */ mpi_normalize (data); mpi_fdiv_r (data, data, sk.n); /* Allocate MPI for the plaintext. */ plain = mpi_snew (ctx.nbits); /* 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 ((ctx.flags & PUBKEY_FLAG_NO_BLINDING)) secret (plain, data, &sk); else secret_blinded (plain, data, &sk, ctx.nbits); if (DBG_CIPHER) log_printmpi ("rsa_decrypt res", plain); /* Reverse the encoding and build the s-expression. */ switch (ctx.encoding) { case PUBKEY_ENC_PKCS1: rc = _gcry_rsa_pkcs1_decode_for_enc (&unpad, &unpadlen, ctx.nbits, plain); mpi_free (plain); plain = NULL; if (!rc) rc = sexp_build (r_plain, NULL, "(value %b)", (int)unpadlen, unpad); break; case PUBKEY_ENC_OAEP: rc = _gcry_rsa_oaep_decode (&unpad, &unpadlen, ctx.nbits, ctx.hash_algo, plain, ctx.label, ctx.labellen); mpi_free (plain); plain = NULL; if (!rc) rc = sexp_build (r_plain, NULL, "(value %b)", (int)unpadlen, unpad); break; default: /* Raw format. For backward compatibility we need to assume a signed mpi by using the sexp format string "%m". */ rc = sexp_build (r_plain, NULL, (ctx.flags & PUBKEY_FLAG_LEGACYRESULT) ? "%m":"(value %m)", plain); break; } leave: xfree (unpad); _gcry_mpi_release (plain); _gcry_mpi_release (sk.n); _gcry_mpi_release (sk.e); _gcry_mpi_release (sk.d); _gcry_mpi_release (sk.p); _gcry_mpi_release (sk.q); _gcry_mpi_release (sk.u); _gcry_mpi_release (data); sexp_release (l1); _gcry_pk_util_free_encoding_ctx (&ctx); if (DBG_CIPHER) log_debug ("rsa_decrypt => %s\n", gpg_strerror (rc)); return rc; } static gcry_err_code_t rsa_sign (gcry_sexp_t *r_sig, gcry_sexp_t s_data, gcry_sexp_t keyparms) { gpg_err_code_t rc; struct pk_encoding_ctx ctx; gcry_mpi_t data = NULL; RSA_secret_key sk = {NULL, NULL, NULL, NULL, NULL, NULL}; RSA_public_key pk; gcry_mpi_t sig = NULL; gcry_mpi_t result = NULL; _gcry_pk_util_init_encoding_ctx (&ctx, PUBKEY_OP_SIGN, rsa_get_nbits (keyparms)); /* Extract the data. */ rc = _gcry_pk_util_data_to_mpi (s_data, &data, &ctx); if (rc) goto leave; if (DBG_CIPHER) log_printmpi ("rsa_sign data", data); if (mpi_is_opaque (data)) { rc = GPG_ERR_INV_DATA; goto leave; } /* Extract the key. */ rc = sexp_extract_param (keyparms, NULL, "nedp?q?u?", &sk.n, &sk.e, &sk.d, &sk.p, &sk.q, &sk.u, NULL); if (rc) goto leave; if (DBG_CIPHER) { log_printmpi ("rsa_sign n", sk.n); log_printmpi ("rsa_sign e", sk.e); if (!fips_mode ()) { log_printmpi ("rsa_sign d", sk.d); log_printmpi ("rsa_sign p", sk.p); log_printmpi ("rsa_sign q", sk.q); log_printmpi ("rsa_sign u", sk.u); } } /* Do RSA computation. */ sig = mpi_new (0); if ((ctx.flags & PUBKEY_FLAG_NO_BLINDING)) secret (sig, data, &sk); else secret_blinded (sig, data, &sk, ctx.nbits); if (DBG_CIPHER) log_printmpi ("rsa_sign res", sig); /* Check that the created signature is good. This detects a failure of the CRT algorithm (Lenstra's attack on RSA's use of the CRT). */ result = mpi_new (0); pk.n = sk.n; pk.e = sk.e; public (result, sig, &pk); if (mpi_cmp (result, data)) { rc = GPG_ERR_BAD_SIGNATURE; goto leave; } /* Convert the result. */ if ((ctx.flags & PUBKEY_FLAG_FIXEDLEN)) { /* We need to make sure to return the correct length to avoid problems with missing leading zeroes. */ unsigned char *em; size_t emlen = (mpi_get_nbits (sk.n)+7)/8; rc = _gcry_mpi_to_octet_string (&em, NULL, sig, emlen); if (!rc) { rc = sexp_build (r_sig, NULL, "(sig-val(rsa(s%b)))", (int)emlen, em); xfree (em); } } else rc = sexp_build (r_sig, NULL, "(sig-val(rsa(s%M)))", sig); leave: _gcry_mpi_release (result); _gcry_mpi_release (sig); _gcry_mpi_release (sk.n); _gcry_mpi_release (sk.e); _gcry_mpi_release (sk.d); _gcry_mpi_release (sk.p); _gcry_mpi_release (sk.q); _gcry_mpi_release (sk.u); _gcry_mpi_release (data); _gcry_pk_util_free_encoding_ctx (&ctx); if (DBG_CIPHER) log_debug ("rsa_sign => %s\n", gpg_strerror (rc)); return rc; } static gcry_err_code_t rsa_verify (gcry_sexp_t s_sig, gcry_sexp_t s_data, gcry_sexp_t keyparms) { gcry_err_code_t rc; struct pk_encoding_ctx ctx; gcry_sexp_t l1 = NULL; gcry_mpi_t sig = NULL; gcry_mpi_t data = NULL; RSA_public_key pk = { NULL, NULL }; gcry_mpi_t result = NULL; _gcry_pk_util_init_encoding_ctx (&ctx, PUBKEY_OP_VERIFY, rsa_get_nbits (keyparms)); /* Extract the data. */ rc = _gcry_pk_util_data_to_mpi (s_data, &data, &ctx); if (rc) goto leave; if (DBG_CIPHER) log_printmpi ("rsa_verify data", data); if (mpi_is_opaque (data)) { rc = GPG_ERR_INV_DATA; goto leave; } /* Extract the signature value. */ rc = _gcry_pk_util_preparse_sigval (s_sig, rsa_names, &l1, NULL); if (rc) goto leave; rc = sexp_extract_param (l1, NULL, "s", &sig, NULL); if (rc) goto leave; if (DBG_CIPHER) log_printmpi ("rsa_verify sig", sig); /* Extract the key. */ rc = sexp_extract_param (keyparms, NULL, "ne", &pk.n, &pk.e, NULL); if (rc) goto leave; if (DBG_CIPHER) { log_printmpi ("rsa_verify n", pk.n); log_printmpi ("rsa_verify e", pk.e); } /* Do RSA computation and compare. */ result = mpi_new (0); public (result, sig, &pk); if (DBG_CIPHER) log_printmpi ("rsa_verify cmp", result); if (ctx.verify_cmp) rc = ctx.verify_cmp (&ctx, result); else rc = mpi_cmp (result, data) ? GPG_ERR_BAD_SIGNATURE : 0; leave: _gcry_mpi_release (result); _gcry_mpi_release (pk.n); _gcry_mpi_release (pk.e); _gcry_mpi_release (data); _gcry_mpi_release (sig); sexp_release (l1); _gcry_pk_util_free_encoding_ctx (&ctx); if (DBG_CIPHER) log_debug ("rsa_verify => %s\n", rc?gpg_strerror (rc):"Good"); return rc; } /* Return the number of bits for the key described by PARMS. On error * 0 is returned. The format of PARMS starts with the algorithm name; * for example: * * (rsa * (n ) * (e )) * * More parameters may be given but we only need N here. */ static unsigned int rsa_get_nbits (gcry_sexp_t parms) { gcry_sexp_t l1; gcry_mpi_t n; unsigned int nbits; l1 = sexp_find_token (parms, "n", 1); if (!l1) return 0; /* Parameter N not found. */ n = sexp_nth_mpi (l1, 1, GCRYMPI_FMT_USG); sexp_release (l1); nbits = n? mpi_get_nbits (n) : 0; _gcry_mpi_release (n); return nbits; } /* 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 whether 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 = sexp_find_token (keyparam, "n", 1); if (!l1) return GPG_ERR_NO_OBJ; data = sexp_nth_data (l1, 1, &datalen); if (!data) { sexp_release (l1); return GPG_ERR_NO_OBJ; } _gcry_md_write (md, data, datalen); sexp_release (l1); return 0; } /* Self-test section. */ static const char * selftest_sign_2048 (gcry_sexp_t pkey, gcry_sexp_t skey) { static const char sample_data[] = "(data (flags pkcs1)" " (hash sha256 #11223344556677889900aabbccddeeff" /**/ "102030405060708090a0b0c0d0f01121#))"; static const char sample_data_bad[] = "(data (flags pkcs1)" " (hash sha256 #11223344556677889900aabbccddeeff" /**/ "802030405060708090a0b0c0d0f01121#))"; const char *errtxt = NULL; gcry_error_t err; gcry_sexp_t data = NULL; gcry_sexp_t data_bad = NULL; gcry_sexp_t sig = NULL; /* raw signature data reference */ const char ref_data[] = "6252a19a11e1d5155ed9376036277193d644fa239397fff03e9b92d6f86415d6" "d30da9273775f290e580d038295ff8ff89522becccfa6ae870bf76b76df402a8" "54f69347e3db3de8e1e7d4dada281ec556810c7a8ecd0b5f51f9b1c0e7aa7557" "61aa2b8ba5f811304acc6af0eca41fe49baf33bf34eddaf44e21e036ac7f0b68" "03cdef1c60021fb7b5b97ebacdd88ab755ce29af568dbc5728cc6e6eff42618d" "62a0386ca8beed46402bdeeef29b6a3feded906bace411a06a39192bf516ae10" "67e4320fa8ea113968525f4574d022a3ceeaafdc41079efe1f22cc94bf59d8d3" "328085da9674857db56de5978a62394aab48aa3b72e23a1b16260cfd9daafe65"; gcry_mpi_t ref_mpi = NULL; gcry_mpi_t sig_mpi = NULL; err = sexp_sscan (&data, NULL, sample_data, strlen (sample_data)); if (!err) err = 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_mpi_scan(&ref_mpi, GCRYMPI_FMT_HEX, ref_data, 0, NULL); if (err) { errtxt = "converting ref_data to mpi failed"; goto leave; } err = _gcry_sexp_extract_param(sig, "sig-val!rsa", "s", &sig_mpi, NULL); if (err) { errtxt = "extracting signature data failed"; goto leave; } if (mpi_cmp (sig_mpi, ref_mpi)) { errtxt = "signature does not match reference data"; 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: sexp_release (sig); sexp_release (data_bad); sexp_release (data); _gcry_mpi_release (ref_mpi); _gcry_mpi_release (sig_mpi); 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 = sexp_find_token (encr_data, "enc-val", 0); if (!l1) return NULL; l2 = sexp_find_token (l1, "rsa", 0); sexp_release (l1); if (!l2) return NULL; l3 = sexp_find_token (l2, "a", 0); sexp_release (l2); if (!l3) return NULL; a_value = sexp_nth_mpi (l3, 1, 0); sexp_release (l3); return a_value; } static const char * selftest_encr_2048 (gcry_sexp_t pkey, gcry_sexp_t skey) { const char *errtxt = NULL; gcry_error_t err; static const char plaintext[] = "Jim quickly realized that the beautiful gowns are expensive."; gcry_sexp_t plain = NULL; gcry_sexp_t encr = NULL; gcry_mpi_t ciphertext = NULL; gcry_sexp_t decr = NULL; char *decr_plaintext = NULL; gcry_sexp_t tmplist = NULL; /* expected result of encrypting the plaintext with sample_secret_key */ static const char ref_data[] = "18022e2593a402a737caaa93b4c7e750e20ca265452980e1d6b7710fbd3e" "7dce72be5c2110fb47691cb38f42170ee3b4a37f2498d4a51567d762585e" "4cb81d04fbc7df4144f8e5eac2d4b8688521b64011f11d7ad53f4c874004" "819856f2e2a6f83d1c9c4e73ac26089789c14482b0b8d44139133c88c4a5" "2dba9dd6d6ffc622666b7d129168333d999706af30a2d7d272db7734e5ed" "fb8c64ea3018af3ad20f4a013a5060cb0f5e72753967bebe294280a6ed0d" "dbd3c4f11d0a8696e9d32a0dc03deb0b5e49b2cbd1503392642d4e1211f3" "e8e2ee38abaa3671ccd57fcde8ca76e85fd2cb77c35706a970a213a27352" "cec92a9604d543ddb5fc478ff50e0622"; gcry_mpi_t ref_mpi = NULL; /* Put the plaintext into an S-expression. */ err = sexp_build (&plain, NULL, "(data (flags raw) (value %s))", plaintext); if (err) { errtxt = "converting data failed"; goto leave; } /* Encrypt. */ err = _gcry_pk_encrypt (&encr, plain, pkey); if (err) { errtxt = "encrypt failed"; goto leave; } err = _gcry_mpi_scan(&ref_mpi, GCRYMPI_FMT_HEX, ref_data, 0, NULL); if (err) { errtxt = "converting encrydata to mpi failed"; goto leave; } /* Extraxt the ciphertext from the returned S-expression. */ /*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_printmpi ("plaintext", plaintext); */ /* _gcry_log_printmpi ("ciphertxt", ciphertext); */ if (mpi_cmp (ref_mpi, ciphertext)) { errtxt = "ciphertext doesn't match reference data"; 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 = sexp_find_token (decr, "value", 0); if (tmplist) decr_plaintext = sexp_nth_string (tmplist, 1); else decr_plaintext = sexp_nth_string (decr, 0); if (!decr_plaintext) { errtxt = "decrypt returned no plaintext"; goto leave; } /* Check that the decrypted plaintext matches the original plaintext. */ if (strcmp (plaintext, decr_plaintext)) { errtxt = "mismatch"; goto leave; } leave: sexp_release (tmplist); xfree (decr_plaintext); sexp_release (decr); _gcry_mpi_release (ciphertext); _gcry_mpi_release (ref_mpi); sexp_release (encr); sexp_release (plain); 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 = sexp_sscan (&skey, NULL, sample_secret_key, strlen (sample_secret_key)); if (!err) err = 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_2048 (pkey, skey); if (errtxt) goto failed; what = "encrypt"; errtxt = selftest_encr_2048 (pkey, skey); if (errtxt) goto failed; sexp_release (pkey); sexp_release (skey); return 0; /* Succeeded. */ failed: sexp_release (pkey); 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; } gcry_pk_spec_t _gcry_pubkey_spec_rsa = { GCRY_PK_RSA, { 0, 1 }, (GCRY_PK_USAGE_SIGN | GCRY_PK_USAGE_ENCR), "RSA", rsa_names, "ne", "nedpqu", "a", "s", "n", rsa_generate, rsa_check_secret_key, rsa_encrypt, rsa_decrypt, rsa_sign, rsa_verify, rsa_get_nbits, run_selftests, compute_keygrip }; diff --git a/compat/clock.c b/compat/clock.c index 7f250f33..2a2c205f 100644 --- a/compat/clock.c +++ b/compat/clock.c @@ -1,36 +1,36 @@ /* clock.c - Replacement for WindowsCE Copyright (C) 2010 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. */ #if HAVE_CONFIG_H #include #endif #ifdef HAVE_W32CE_SYSTEM #include #include #include clock_t _gcry_clock (void) { assert (CLOCKS_PER_SEC == 1000); -#warning Replace by a correct implementaion. +#warning Replace by a correct implementation. /* It seems that GetProcessTimes is available in the kernel but without a declaration. If that fails we would need to walk over all threads and tally up the GetThreadTimes. */ return GetTickCount (); } #else # error No replacement function for clock known #endif diff --git a/configure.ac b/configure.ac index 2609b414..7ea0b6a6 100644 --- a/configure.ac +++ b/configure.ac @@ -1,2675 +1,2675 @@ # Configure.ac script for Libgcrypt # Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2006, # 2007, 2008, 2009, 2011 Free Software Foundation, Inc. # Copyright (C) 2012, 2013, 2014, 2015, 2016 g10 Code GmbH # # 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 . # (Process this file with autoconf to produce a configure script.) AC_REVISION($Revision$) AC_PREREQ(2.60) min_automake_version="1.14" # To build a release you need to create a tag with the version number # (git tag -s libgcrypt-n.m.k) and run "./autogen.sh --force". Please # bump the version number immediately after the release and do another # commit and push so that the git magic is able to work. See below # for the LT versions. m4_define(mym4_version_major, [1]) m4_define(mym4_version_minor, [8]) m4_define(mym4_version_micro, [0]) # Below is m4 magic to extract and compute the revision number, the # decimalized short revision number, a beta version string, and a flag # indicating a development version (mym4_isgit). Note that the m4 # processing is done by autoconf and not during the configure run. m4_define(mym4_version, [mym4_version_major.mym4_version_minor.mym4_version_micro]) m4_define([mym4_revision], m4_esyscmd([git rev-parse --short HEAD | tr -d '\n\r'])) m4_define([mym4_revision_dec], m4_esyscmd_s([echo $((0x$(echo ]mym4_revision[|head -c 4)))])) m4_define([mym4_betastring], m4_esyscmd_s([git describe --match 'libgcrypt-[0-9].*[0-9]' --long|\ awk -F- '$3!=0{print"-beta"$3}'])) m4_define([mym4_isgit],m4_if(mym4_betastring,[],[no],[yes])) m4_define([mym4_full_version],[mym4_version[]mym4_betastring]) AC_INIT([libgcrypt],[mym4_full_version],[http://bugs.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=21 LIBGCRYPT_LT_AGE=1 LIBGCRYPT_LT_REVISION=3 # If the API is changed in an incompatible way: increment the next counter. # # 1.6: ABI and API change but the change is to most users irrelevant # and thus the API version number has not been incremented. LIBGCRYPT_CONFIG_API_VERSION=1 # If you change the required gpg-error version, please remove # unnecessary error code defines in src/gcrypt-int.h. NEED_GPG_ERROR_VERSION=1.25 PACKAGE=$PACKAGE_NAME VERSION=$PACKAGE_VERSION AC_CONFIG_AUX_DIR([build-aux]) AC_CONFIG_SRCDIR([src/libgcrypt.vers]) AM_INIT_AUTOMAKE([serial-tests dist-bzip2]) AC_CONFIG_HEADER(config.h) AC_CONFIG_MACRO_DIR([m4]) AC_CONFIG_LIBOBJ_DIR([compat]) AC_CANONICAL_HOST AM_MAINTAINER_MODE AM_SILENT_RULES AC_ARG_VAR(SYSROOT,[locate config scripts also below that directory]) AH_TOP([ #ifndef _GCRYPT_CONFIG_H_INCLUDED #define _GCRYPT_CONFIG_H_INCLUDED /* Enable gpg-error's strerror macro for W32CE. */ #define GPG_ERR_ENABLE_ERRNO_MACROS 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_ #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]) VERSION_NUMBER=m4_esyscmd(printf "0x%02x%02x%02x" mym4_version_major \ mym4_version_minor mym4_version_micro) AC_SUBST(VERSION_NUMBER) ###################### ## 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_GNU_SOURCE # We need to compile and run a program on the build machine. A # comment in libgpg-error says that the AC_PROG_CC_FOR_BUILD macro in # the AC archive is broken for autoconf 2.57. Given that there is no # newer version of that macro, we assume that it is also broken for # autoconf 2.61 and thus we use a simple but usually sufficient # approach. AC_MSG_CHECKING(for cc for build) if test "$cross_compiling" = "yes"; then CC_FOR_BUILD="${CC_FOR_BUILD-cc}" else CC_FOR_BUILD="${CC_FOR_BUILD-$CC}" fi AC_MSG_RESULT($CC_FOR_BUILD) AC_ARG_VAR(CC_FOR_BUILD,[build system C compiler]) LT_PREREQ([2.2.6]) LT_INIT([win32-dll disable-static]) LT_LANG([Windows Resource]) ########################## ## General definitions. ## ########################## # Used by libgcrypt-config LIBGCRYPT_CONFIG_LIBS="-lgcrypt" LIBGCRYPT_CONFIG_CFLAGS="" LIBGCRYPT_CONFIG_HOST="$host" # Definitions for symmetric ciphers. available_ciphers="arcfour blowfish cast5 des aes twofish serpent rfc2268 seed" available_ciphers="$available_ciphers camellia idea salsa20 gost28147 chacha20" enabled_ciphers="" # Definitions for public-key ciphers. available_pubkey_ciphers="dsa elgamal rsa ecc" enabled_pubkey_ciphers="" # Definitions for message digests. available_digests="crc gostr3411-94 md2 md4 md5 rmd160 sha1 sha256 sha512" available_digests="$available_digests sha3 tiger whirlpool stribog blake2" enabled_digests="" # Definitions for kdfs (optional ones) available_kdfs="s2k pkdf2 scrypt" enabled_kdfs="" # 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 have_w32ce_system=no have_pthread=no # Setup some stuff depending on host. case "${host}" in *-*-mingw32*) ac_cv_have_dev_random=no have_w32_system=yes case "${host}" in *-mingw32ce*) have_w32ce_system=yes available_random_modules="w32ce" ;; *) available_random_modules="w32" ;; esac 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) ;; *-*-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) ;; *-apple-darwin*) AC_DEFINE(_DARWIN_C_SOURCE, 900000L, Expose all libc features (__DARWIN_C_FULL).) ;; *) ;; esac if test "$have_w32_system" = yes; then AC_DEFINE(HAVE_W32_SYSTEM,1, [Defined if we run on a W32 API based system]) if test "$have_w32ce_system" = yes; then AC_DEFINE(HAVE_W32CE_SYSTEM,1,[Defined if we run on WindowsCE]) fi fi AM_CONDITIONAL(HAVE_W32_SYSTEM, test "$have_w32_system" = yes) AM_CONDITIONAL(HAVE_W32CE_SYSTEM, test "$have_w32ce_system" = yes) # A printable OS Name is sometimes useful. case "${host}" in *-*-mingw32ce*) PRINTABLE_OS_NAME="W32CE" ;; *-*-mingw32*) PRINTABLE_OS_NAME="W32" ;; 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]) + AC_DEFINE(DISABLED_ENDIAN_CHECK,1,[configure did not test for endianness]) 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_CHECK_SIZEOF(void *, 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 # Ensure that we have UINT64_C before we bother to check for uint64_t AC_CACHE_CHECK([for UINT64_C],[gnupg_cv_uint64_c_works], AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[uint64_t foo=UINT64_C(42);]])], gnupg_cv_uint64_c_works=yes,gnupg_cv_uint64_c_works=no)) if test "$gnupg_cv_uint64_c_works" = "yes" ; then AC_CHECK_SIZEOF(uint64_t) 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_ERROR([[ *** *** No 64-bit integer type available. *** It is not possible to build Libgcrypt on this platform. ***]]) 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" default_kdfs="$available_kdfs" # Blacklist MD2 by default default_digests=`echo $default_digests | sed -e 's/md2//g'` # Substitutions to set generated files in a Emacs buffer to read-only. AC_SUBST(emacs_local_vars_begin, ['Local Variables:']) AC_SUBST(emacs_local_vars_read_only, ['buffer-read-only: t']) AC_SUBST(emacs_local_vars_end, ['End:']) ############################ ## 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-kdfs switch. AC_ARG_ENABLE(kdfs, AC_HELP_STRING([--enable-kfds=kdfs], [select the KDFs to include]), [enabled_kdfs=`echo $enableval | tr ',:' ' ' | tr '[A-Z]' '[a-z]'`], [enabled_kdfs=""]) if test "x$enabled_kdfs" = "x" \ -o "$enabled_kdfs" = "yes" \ -o "$enabled_kdfs" = "no"; then enabled_kdfs=$default_kdfs fi AC_MSG_CHECKING([which key derivation functions to include]) for kdf in $enabled_kdfs; do LIST_MEMBER($kdf, $available_kdfs) if test "$found" = "0"; then AC_MSG_ERROR([unsupported key derivation function specified]) fi done AC_MSG_RESULT([$enabled_kdfs]) # 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 --enable-large-data-tests switch. AC_MSG_CHECKING([whether to run large data tests]) AC_ARG_ENABLE(large-data-tests, AC_HELP_STRING([--enable-large-data-tests], [Enable the real long ruinning large data tests]), large_data_tests=$enableval,large_data_tests=no) AC_MSG_RESULT($large_data_tests) AC_SUBST(RUN_LARGE_DATA_TESTS, $large_data_tests) # 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) # Implementation of the --disable-aesni-support switch. AC_MSG_CHECKING([whether AESNI support is requested]) AC_ARG_ENABLE(aesni-support, AC_HELP_STRING([--disable-aesni-support], [Disable support for the Intel AES-NI instructions]), aesnisupport=$enableval,aesnisupport=yes) AC_MSG_RESULT($aesnisupport) # Implementation of the --disable-pclmul-support switch. AC_MSG_CHECKING([whether PCLMUL support is requested]) AC_ARG_ENABLE(pclmul-support, AC_HELP_STRING([--disable-pclmul-support], [Disable support for the Intel PCLMUL instructions]), pclmulsupport=$enableval,pclmulsupport=yes) AC_MSG_RESULT($pclmulsupport) # Implementation of the --disable-sse41-support switch. AC_MSG_CHECKING([whether SSE4.1 support is requested]) AC_ARG_ENABLE(sse41-support, AC_HELP_STRING([--disable-sse41-support], [Disable support for the Intel SSE4.1 instructions]), sse41support=$enableval,sse41support=yes) AC_MSG_RESULT($sse41support) # Implementation of the --disable-drng-support switch. AC_MSG_CHECKING([whether DRNG support is requested]) AC_ARG_ENABLE(drng-support, AC_HELP_STRING([--disable-drng-support], [Disable support for the Intel DRNG (RDRAND instruction)]), drngsupport=$enableval,drngsupport=yes) AC_MSG_RESULT($drngsupport) # Implementation of the --disable-avx-support switch. AC_MSG_CHECKING([whether AVX support is requested]) AC_ARG_ENABLE(avx-support, AC_HELP_STRING([--disable-avx-support], [Disable support for the Intel AVX instructions]), avxsupport=$enableval,avxsupport=yes) AC_MSG_RESULT($avxsupport) # Implementation of the --disable-avx2-support switch. AC_MSG_CHECKING([whether AVX2 support is requested]) AC_ARG_ENABLE(avx2-support, AC_HELP_STRING([--disable-avx2-support], [Disable support for the Intel AVX2 instructions]), avx2support=$enableval,avx2support=yes) AC_MSG_RESULT($avx2support) # Implementation of the --disable-neon-support switch. AC_MSG_CHECKING([whether NEON support is requested]) AC_ARG_ENABLE(neon-support, AC_HELP_STRING([--disable-neon-support], [Disable support for the ARM NEON instructions]), neonsupport=$enableval,neonsupport=yes) AC_MSG_RESULT($neonsupport) # Implementation of the --disable-arm-crypto-support switch. AC_MSG_CHECKING([whether ARMv8 Crypto Extension support is requested]) AC_ARG_ENABLE(arm-crypto-support, AC_HELP_STRING([--disable-arm-crypto-support], [Disable support for the ARMv8 Crypto Extension instructions]), armcryptosupport=$enableval,armcryptosupport=yes) AC_MSG_RESULT($armcryptosupport) # Implementation of the --disable-O-flag-munging switch. AC_MSG_CHECKING([whether a -O flag munging is requested]) AC_ARG_ENABLE([O-flag-munging], AC_HELP_STRING([--disable-O-flag-munging], [Disable modification of the cc -O flag]), [enable_o_flag_munging=$enableval], [enable_o_flag_munging=yes]) AC_MSG_RESULT($enable_o_flag_munging) AM_CONDITIONAL(ENABLE_O_FLAG_MUNGING, test "$enable_o_flag_munging" = "yes") # Implementation of the --disable-amd64-as-feature-detection switch. AC_MSG_CHECKING([whether to enable AMD64 as(1) feature detection]) AC_ARG_ENABLE(amd64-as-feature-detection, AC_HELP_STRING([--disable-amd64-as-feature-detection], [Disable the auto-detection of AMD64 as(1) features]), amd64_as_feature_detection=$enableval, amd64_as_feature_detection=yes) AC_MSG_RESULT($amd64_as_feature_detection) 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) # # Check whether pthreads is available # if test "$have_w32_system" != yes; then AC_CHECK_LIB(pthread,pthread_create,have_pthread=yes) if test "$have_pthread" = yes; then AC_DEFINE(HAVE_PTHREAD, 1 ,[Define if we have pthread.]) fi fi # 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 sys/msg.h) INSERT_SYS_SELECT_H= if test x"$ac_cv_header_sys_select_h" = xyes; then INSERT_SYS_SELECT_H=" include " fi AC_SUBST(INSERT_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 AC_TYPE_PID_T 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 __builtin_bswap32 intrinsic. # AC_CACHE_CHECK(for __builtin_bswap32, [gcry_cv_have_builtin_bswap32], [gcry_cv_have_builtin_bswap32=no AC_LINK_IFELSE([AC_LANG_PROGRAM([], [int x = 0; int y = __builtin_bswap32(x); return y;])], [gcry_cv_have_builtin_bswap32=yes])]) if test "$gcry_cv_have_builtin_bswap32" = "yes" ; then AC_DEFINE(HAVE_BUILTIN_BSWAP32,1, [Defined if compiler has '__builtin_bswap32' intrinsic]) fi # # Check for __builtin_bswap64 intrinsic. # AC_CACHE_CHECK(for __builtin_bswap64, [gcry_cv_have_builtin_bswap64], [gcry_cv_have_builtin_bswap64=no AC_LINK_IFELSE([AC_LANG_PROGRAM([], [long long x = 0; long long y = __builtin_bswap64(x); return y;])], [gcry_cv_have_builtin_bswap64=yes])]) if test "$gcry_cv_have_builtin_bswap64" = "yes" ; then AC_DEFINE(HAVE_BUILTIN_BSWAP64,1, [Defined if compiler has '__builtin_bswap64' intrinsic]) fi # # Check for __builtin_ctz intrinsic. # AC_CACHE_CHECK(for __builtin_ctz, [gcry_cv_have_builtin_ctz], [gcry_cv_have_builtin_ctz=no AC_LINK_IFELSE([AC_LANG_PROGRAM([], [unsigned int x = 0; int y = __builtin_ctz(x); return y;])], [gcry_cv_have_builtin_ctz=yes])]) if test "$gcry_cv_have_builtin_ctz" = "yes" ; then AC_DEFINE(HAVE_BUILTIN_CTZ, 1, [Defined if compiler has '__builtin_ctz' intrinsic]) fi # # Check for VLA support (variable length arrays). # AC_CACHE_CHECK(whether the variable length arrays are supported, [gcry_cv_have_vla], [gcry_cv_have_vla=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[void f1(char *, int); char foo(int i) { char b[(i < 0 ? 0 : i) + 1]; f1(b, sizeof b); return b[0];}]])], [gcry_cv_have_vla=yes])]) if test "$gcry_cv_have_vla" = "yes" ; then AC_DEFINE(HAVE_VLA,1, [Defined if variable length arrays are supported]) fi # # 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 # Following attribute tests depend on warnings to cause compile to fail, # so set -Werror temporarily. _gcc_cflags_save=$CFLAGS CFLAGS="$CFLAGS -Werror" # # Check whether the compiler supports the GCC style aligned attribute # AC_CACHE_CHECK([whether the GCC style aligned attribute is supported], [gcry_cv_gcc_attribute_aligned], [gcry_cv_gcc_attribute_aligned=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[struct { int a; } foo __attribute__ ((aligned (16)));]])], [gcry_cv_gcc_attribute_aligned=yes])]) if test "$gcry_cv_gcc_attribute_aligned" = "yes" ; then AC_DEFINE(HAVE_GCC_ATTRIBUTE_ALIGNED,1, [Defined if a GCC style "__attribute__ ((aligned (n))" is supported]) fi # # Check whether the compiler supports the GCC style packed attribute # AC_CACHE_CHECK([whether the GCC style packed attribute is supported], [gcry_cv_gcc_attribute_packed], [gcry_cv_gcc_attribute_packed=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[struct foolong_s { long b; } __attribute__ ((packed)); struct foo_s { char a; struct foolong_s b; } __attribute__ ((packed)); enum bar { FOO = 1 / (sizeof(struct foo_s) == (sizeof(char) + sizeof(long))), };]])], [gcry_cv_gcc_attribute_packed=yes])]) if test "$gcry_cv_gcc_attribute_packed" = "yes" ; then AC_DEFINE(HAVE_GCC_ATTRIBUTE_PACKED,1, [Defined if a GCC style "__attribute__ ((packed))" is supported]) fi # # Check whether the compiler supports the GCC style may_alias attribute # AC_CACHE_CHECK([whether the GCC style may_alias attribute is supported], [gcry_cv_gcc_attribute_may_alias], [gcry_cv_gcc_attribute_may_alias=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[typedef struct foo_s { int a; } __attribute__ ((may_alias)) foo_t;]])], [gcry_cv_gcc_attribute_may_alias=yes])]) if test "$gcry_cv_gcc_attribute_may_alias" = "yes" ; then AC_DEFINE(HAVE_GCC_ATTRIBUTE_MAY_ALIAS,1, [Defined if a GCC style "__attribute__ ((may_alias))" is supported]) fi # Restore flags. CFLAGS=$_gcc_cflags_save; # # Check whether the compiler supports 'asm' or '__asm__' keyword for # assembler blocks. # AC_CACHE_CHECK([whether 'asm' assembler keyword is supported], [gcry_cv_have_asm], [gcry_cv_have_asm=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[void a(void) { asm("":::"memory"); }]])], [gcry_cv_have_asm=yes])]) AC_CACHE_CHECK([whether '__asm__' assembler keyword is supported], [gcry_cv_have___asm__], [gcry_cv_have___asm__=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[void a(void) { __asm__("":::"memory"); }]])], [gcry_cv_have___asm__=yes])]) if test "$gcry_cv_have_asm" = "no" ; then if test "$gcry_cv_have___asm__" = "yes" ; then AC_DEFINE(asm,__asm__, [Define to supported assembler block keyword, if plain 'asm' was not supported]) fi fi # # Check whether the compiler supports inline assembly memory barrier. # if test "$gcry_cv_have_asm" = "no" ; then if test "$gcry_cv_have___asm__" = "yes" ; then AC_CACHE_CHECK([whether inline assembly memory barrier is supported], [gcry_cv_have_asm_volatile_memory], [gcry_cv_have_asm_volatile_memory=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[void a(void) { __asm__ volatile("":::"memory"); }]])], [gcry_cv_have_asm_volatile_memory=yes])]) fi else AC_CACHE_CHECK([whether inline assembly memory barrier is supported], [gcry_cv_have_asm_volatile_memory], [gcry_cv_have_asm_volatile_memory=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[void a(void) { asm volatile("":::"memory"); }]])], [gcry_cv_have_asm_volatile_memory=yes])]) fi if test "$gcry_cv_have_asm_volatile_memory" = "yes" ; then AC_DEFINE(HAVE_GCC_ASM_VOLATILE_MEMORY,1, [Define if inline asm memory barrier is supported]) fi # # Check whether GCC assembler supports features needed for our ARM # implementations. This needs to be done before setting up the # assembler stuff. # AC_CACHE_CHECK([whether GCC assembler is compatible for ARM assembly implementations], [gcry_cv_gcc_arm_platform_as_ok], [gcry_cv_gcc_arm_platform_as_ok=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[__asm__( /* Test if assembler supports UAL syntax. */ ".syntax unified\n\t" ".arm\n\t" /* our assembly code is in ARM mode */ /* Following causes error if assembler ignored '.syntax unified'. */ "asmfunc:\n\t" "add %r0, %r0, %r4, ror #12;\n\t" /* Test if '.type' and '.size' are supported. */ ".size asmfunc,.-asmfunc;\n\t" ".type asmfunc,%function;\n\t" );]])], [gcry_cv_gcc_arm_platform_as_ok=yes])]) if test "$gcry_cv_gcc_arm_platform_as_ok" = "yes" ; then AC_DEFINE(HAVE_COMPATIBLE_GCC_ARM_PLATFORM_AS,1, [Defined if underlying assembler is compatible with ARM assembly implementations]) fi # # Check whether GCC assembler supports features needed for our ARMv8/Aarch64 # implementations. This needs to be done before setting up the # assembler stuff. # AC_CACHE_CHECK([whether GCC assembler is compatible for ARMv8/Aarch64 assembly implementations], [gcry_cv_gcc_aarch64_platform_as_ok], [gcry_cv_gcc_aarch64_platform_as_ok=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[__asm__( "asmfunc:\n\t" "eor x0, x0, x30, ror #12;\n\t" "add x0, x0, x30, asr #12;\n\t" "eor v0.16b, v0.16b, v31.16b;\n\t" /* Test if '.type' and '.size' are supported. */ ".size asmfunc,.-asmfunc;\n\t" ".type asmfunc,@function;\n\t" );]])], [gcry_cv_gcc_aarch64_platform_as_ok=yes])]) if test "$gcry_cv_gcc_aarch64_platform_as_ok" = "yes" ; then AC_DEFINE(HAVE_COMPATIBLE_GCC_AARCH64_PLATFORM_AS,1, [Defined if underlying assembler is compatible with ARMv8/Aarch64 assembly implementations]) fi # # Check whether underscores in symbols are required. This needs to be # done before setting up the assembler stuff. # GNUPG_SYS_SYMBOL_UNDERSCORE() ################################# #### #### #### Setup assembler stuff. #### #### Define mpi_cpu_arch. #### #### #### ################################# 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(architecture and 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($mpi_cpu_arch) 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) # Reset non applicable feature flags. if test "$mpi_cpu_arch" != "x86" ; then aesnisupport="n/a" pclmulsupport="n/a" sse41support="n/a" avxsupport="n/a" avx2support="n/a" padlocksupport="n/a" drngsupport="n/a" fi if test "$mpi_cpu_arch" != "arm" ; then if test "$mpi_cpu_arch" != "aarch64" ; then neonsupport="n/a" armcryptosupport="n/a" fi fi ############################################# #### #### #### Platform specific compiler checks. #### #### #### ############################################# # Following tests depend on warnings to cause compile to fail, so set -Werror # temporarily. _gcc_cflags_save=$CFLAGS CFLAGS="$CFLAGS -Werror" # # Check whether compiler supports 'ms_abi' function attribute. # AC_CACHE_CHECK([whether compiler supports 'ms_abi' function attribute], [gcry_cv_gcc_attribute_ms_abi], [gcry_cv_gcc_attribute_ms_abi=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[int __attribute__ ((ms_abi)) proto(int);]])], [gcry_cv_gcc_attribute_ms_abi=yes])]) if test "$gcry_cv_gcc_attribute_ms_abi" = "yes" ; then AC_DEFINE(HAVE_GCC_ATTRIBUTE_MS_ABI,1, [Defined if compiler supports "__attribute__ ((ms_abi))" function attribute]) fi # # Check whether compiler supports 'sysv_abi' function attribute. # AC_CACHE_CHECK([whether compiler supports 'sysv_abi' function attribute], [gcry_cv_gcc_attribute_sysv_abi], [gcry_cv_gcc_attribute_sysv_abi=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[int __attribute__ ((sysv_abi)) proto(int);]])], [gcry_cv_gcc_attribute_sysv_abi=yes])]) if test "$gcry_cv_gcc_attribute_sysv_abi" = "yes" ; then AC_DEFINE(HAVE_GCC_ATTRIBUTE_SYSV_ABI,1, [Defined if compiler supports "__attribute__ ((sysv_abi))" function attribute]) fi # # Check whether default calling convention is 'ms_abi'. # if test "$gcry_cv_gcc_attribute_ms_abi" = "yes" ; then AC_CACHE_CHECK([whether default calling convention is 'ms_abi'], [gcry_cv_gcc_default_abi_is_ms_abi], [gcry_cv_gcc_default_abi_is_ms_abi=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[void *test(void) { void *(*def_func)(void) = test; void *__attribute__((ms_abi))(*msabi_func)(void); /* warning on SysV abi targets, passes on Windows based targets */ msabi_func = def_func; return msabi_func; }]])], [gcry_cv_gcc_default_abi_is_ms_abi=yes])]) if test "$gcry_cv_gcc_default_abi_is_ms_abi" = "yes" ; then AC_DEFINE(HAVE_GCC_DEFAULT_ABI_IS_MS_ABI,1, [Defined if default calling convention is 'ms_abi']) fi fi # # Check whether default calling convention is 'sysv_abi'. # if test "$gcry_cv_gcc_attribute_sysv_abi" = "yes" ; then AC_CACHE_CHECK([whether default calling convention is 'sysv_abi'], [gcry_cv_gcc_default_abi_is_sysv_abi], [gcry_cv_gcc_default_abi_is_sysv_abi=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[void *test(void) { void *(*def_func)(void) = test; void *__attribute__((sysv_abi))(*sysvabi_func)(void); /* warning on MS ABI targets, passes on SysV ABI targets */ sysvabi_func = def_func; return sysvabi_func; }]])], [gcry_cv_gcc_default_abi_is_sysv_abi=yes])]) if test "$gcry_cv_gcc_default_abi_is_sysv_abi" = "yes" ; then AC_DEFINE(HAVE_GCC_DEFAULT_ABI_IS_SYSV_ABI,1, [Defined if default calling convention is 'sysv_abi']) fi fi # Restore flags. CFLAGS=$_gcc_cflags_save; # # Check whether GCC inline assembler supports SSSE3 instructions # This is required for the AES-NI instructions. # AC_CACHE_CHECK([whether GCC inline assembler supports SSSE3 instructions], [gcry_cv_gcc_inline_asm_ssse3], [if test "$mpi_cpu_arch" != "x86" ; then gcry_cv_gcc_inline_asm_ssse3="n/a" else gcry_cv_gcc_inline_asm_ssse3=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[static unsigned char be_mask[16] __attribute__ ((aligned (16))) = { 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }; void a(void) { __asm__("pshufb %[mask], %%xmm2\n\t"::[mask]"m"(*be_mask):); }]])], [gcry_cv_gcc_inline_asm_ssse3=yes]) fi]) if test "$gcry_cv_gcc_inline_asm_ssse3" = "yes" ; then AC_DEFINE(HAVE_GCC_INLINE_ASM_SSSE3,1, [Defined if inline assembler supports SSSE3 instructions]) fi # # Check whether GCC inline assembler supports PCLMUL instructions. # AC_CACHE_CHECK([whether GCC inline assembler supports PCLMUL instructions], [gcry_cv_gcc_inline_asm_pclmul], [if test "$mpi_cpu_arch" != "x86" ; then gcry_cv_gcc_inline_asm_pclmul="n/a" else gcry_cv_gcc_inline_asm_pclmul=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[void a(void) { __asm__("pclmulqdq \$0, %%xmm1, %%xmm3\n\t":::"cc"); }]])], [gcry_cv_gcc_inline_asm_pclmul=yes]) fi]) if test "$gcry_cv_gcc_inline_asm_pclmul" = "yes" ; then AC_DEFINE(HAVE_GCC_INLINE_ASM_PCLMUL,1, [Defined if inline assembler supports PCLMUL instructions]) fi # # Check whether GCC inline assembler supports SSE4.1 instructions. # AC_CACHE_CHECK([whether GCC inline assembler supports SSE4.1 instructions], [gcry_cv_gcc_inline_asm_sse41], [if test "$mpi_cpu_arch" != "x86" ; then gcry_cv_gcc_inline_asm_sse41="n/a" else gcry_cv_gcc_inline_asm_sse41=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[void a(void) { int i; __asm__("pextrd \$2, %%xmm0, %[out]\n\t" : [out] "=m" (i)); }]])], [gcry_cv_gcc_inline_asm_sse41=yes]) fi]) if test "$gcry_cv_gcc_inline_asm_sse41" = "yes" ; then AC_DEFINE(HAVE_GCC_INLINE_ASM_SSE41,1, [Defined if inline assembler supports SSE4.1 instructions]) fi # # Check whether GCC inline assembler supports AVX instructions # AC_CACHE_CHECK([whether GCC inline assembler supports AVX instructions], [gcry_cv_gcc_inline_asm_avx], [if test "$mpi_cpu_arch" != "x86" ; then gcry_cv_gcc_inline_asm_avx="n/a" else gcry_cv_gcc_inline_asm_avx=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[void a(void) { __asm__("xgetbv; vaesdeclast (%[mem]),%%xmm0,%%xmm7\n\t"::[mem]"r"(0):); }]])], [gcry_cv_gcc_inline_asm_avx=yes]) fi]) if test "$gcry_cv_gcc_inline_asm_avx" = "yes" ; then AC_DEFINE(HAVE_GCC_INLINE_ASM_AVX,1, [Defined if inline assembler supports AVX instructions]) fi # # Check whether GCC inline assembler supports AVX2 instructions # AC_CACHE_CHECK([whether GCC inline assembler supports AVX2 instructions], [gcry_cv_gcc_inline_asm_avx2], [if test "$mpi_cpu_arch" != "x86" ; then gcry_cv_gcc_inline_asm_avx2="n/a" else gcry_cv_gcc_inline_asm_avx2=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[void a(void) { __asm__("xgetbv; vpbroadcastb %%xmm7,%%ymm1\n\t":::"cc"); }]])], [gcry_cv_gcc_inline_asm_avx2=yes]) fi]) if test "$gcry_cv_gcc_inline_asm_avx2" = "yes" ; then AC_DEFINE(HAVE_GCC_INLINE_ASM_AVX2,1, [Defined if inline assembler supports AVX2 instructions]) fi # # Check whether GCC inline assembler supports BMI2 instructions # AC_CACHE_CHECK([whether GCC inline assembler supports BMI2 instructions], [gcry_cv_gcc_inline_asm_bmi2], [if test "$mpi_cpu_arch" != "x86" ; then gcry_cv_gcc_inline_asm_bmi2="n/a" else gcry_cv_gcc_inline_asm_bmi2=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[void a(void) { __asm__("rorxl \$23, %%eax, %%edx\\n\\t":::"memory"); }]])], [gcry_cv_gcc_inline_asm_bmi2=yes]) fi]) if test "$gcry_cv_gcc_inline_asm_bmi2" = "yes" ; then AC_DEFINE(HAVE_GCC_INLINE_ASM_BMI2,1, [Defined if inline assembler supports BMI2 instructions]) fi # # Check whether GCC assembler needs "-Wa,--divide" to correctly handle # constant division # if test $amd64_as_feature_detection = yes; then AC_CACHE_CHECK([whether GCC assembler handles division correctly], [gcry_cv_gcc_as_const_division_ok], [gcry_cv_gcc_as_const_division_ok=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[__asm__("xorl \$(123456789/12345678), %ebp;\n\t");]])], [gcry_cv_gcc_as_const_division_ok=yes])]) if test "$gcry_cv_gcc_as_const_division_ok" = "no" ; then # # Add '-Wa,--divide' to CPPFLAGS and try check again. # _gcc_cppflags_save="$CPPFLAGS" CPPFLAGS="$CPPFLAGS -Wa,--divide" AC_CACHE_CHECK([whether GCC assembler handles division correctly with "-Wa,--divide"], [gcry_cv_gcc_as_const_division_with_wadivide_ok], [gcry_cv_gcc_as_const_division_with_wadivide_ok=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[__asm__("xorl \$(123456789/12345678), %ebp;\n\t");]])], [gcry_cv_gcc_as_const_division_with_wadivide_ok=yes])]) if test "$gcry_cv_gcc_as_const_division_with_wadivide_ok" = "no" ; then # '-Wa,--divide' did not work, restore old flags. CPPFLAGS="$_gcc_cppflags_save" fi fi fi # # Check whether GCC assembler supports features needed for our amd64 # implementations # if test $amd64_as_feature_detection = yes; then AC_CACHE_CHECK([whether GCC assembler is compatible for amd64 assembly implementations], [gcry_cv_gcc_amd64_platform_as_ok], [if test "$mpi_cpu_arch" != "x86" ; then gcry_cv_gcc_amd64_platform_as_ok="n/a" else gcry_cv_gcc_amd64_platform_as_ok=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[__asm__( /* Test if '.type' and '.size' are supported. */ /* These work only on ELF targets. */ "asmfunc:\n\t" ".size asmfunc,.-asmfunc;\n\t" ".type asmfunc,@function;\n\t" /* Test if assembler allows use of '/' for constant division * (Solaris/x86 issue). If previous constant division check * and "-Wa,--divide" workaround failed, this causes assembly * to be disable on this machine. */ "xorl \$(123456789/12345678), %ebp;\n\t" );]])], [gcry_cv_gcc_amd64_platform_as_ok=yes]) fi]) if test "$gcry_cv_gcc_amd64_platform_as_ok" = "yes" ; then AC_DEFINE(HAVE_COMPATIBLE_GCC_AMD64_PLATFORM_AS,1, [Defined if underlying assembler is compatible with amd64 assembly implementations]) fi if test "$gcry_cv_gcc_amd64_platform_as_ok" = "no" && test "$gcry_cv_gcc_attribute_sysv_abi" = "yes" && test "$gcry_cv_gcc_default_abi_is_ms_abi" = "yes"; then AC_CACHE_CHECK([whether GCC assembler is compatible for WIN64 assembly implementations], [gcry_cv_gcc_win64_platform_as_ok], [gcry_cv_gcc_win64_platform_as_ok=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[__asm__( ".globl asmfunc\n\t" "asmfunc:\n\t" "xorq \$(1234), %rbp;\n\t" );]])], [gcry_cv_gcc_win64_platform_as_ok=yes])]) if test "$gcry_cv_gcc_win64_platform_as_ok" = "yes" ; then AC_DEFINE(HAVE_COMPATIBLE_GCC_WIN64_PLATFORM_AS,1, [Defined if underlying assembler is compatible with WIN64 assembly implementations]) fi fi fi # # Check whether GCC assembler supports features needed for assembly # implementations that use Intel syntax # AC_CACHE_CHECK([whether GCC assembler is compatible for Intel syntax assembly implementations], [gcry_cv_gcc_platform_as_ok_for_intel_syntax], [if test "$mpi_cpu_arch" != "x86" ; then gcry_cv_gcc_platform_as_ok_for_intel_syntax="n/a" else gcry_cv_gcc_platform_as_ok_for_intel_syntax=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[__asm__( ".intel_syntax noprefix\n\t" "pxor xmm1, xmm7;\n\t" /* Intel syntax implementation also use GAS macros, so check * for them here. */ "VAL_A = xmm4\n\t" "VAL_B = xmm2\n\t" ".macro SET_VAL_A p1\n\t" " VAL_A = \\\\p1 \n\t" ".endm\n\t" ".macro SET_VAL_B p1\n\t" " VAL_B = \\\\p1 \n\t" ".endm\n\t" "vmovdqa VAL_A, VAL_B;\n\t" "SET_VAL_A eax\n\t" "SET_VAL_B ebp\n\t" "add VAL_A, VAL_B;\n\t" "add VAL_B, 0b10101;\n\t" );]])], [gcry_cv_gcc_platform_as_ok_for_intel_syntax=yes]) fi]) if test "$gcry_cv_gcc_platform_as_ok_for_intel_syntax" = "yes" ; then AC_DEFINE(HAVE_INTEL_SYNTAX_PLATFORM_AS,1, [Defined if underlying assembler is compatible with Intel syntax assembly implementations]) fi # # Check whether compiler is configured for ARMv6 or newer architecture # AC_CACHE_CHECK([whether compiler is configured for ARMv6 or newer architecture], [gcry_cv_cc_arm_arch_is_v6], [if test "$mpi_cpu_arch" != "arm" ; then gcry_cv_cc_arm_arch_is_v6="n/a" else gcry_cv_cc_arm_arch_is_v6=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[ #if defined(__arm__) && \ ((defined(__ARM_ARCH) && __ARM_ARCH >= 6) \ || defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) \ || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) \ || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6T2__) \ || defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) \ || defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) \ || defined(__ARM_ARCH_7EM__)) /* empty */ #else /* fail compile if not ARMv6. */ not_armv6 not_armv6 = (not_armv6)not_armv6; #endif ]])], [gcry_cv_cc_arm_arch_is_v6=yes]) fi]) if test "$gcry_cv_cc_arm_arch_is_v6" = "yes" ; then AC_DEFINE(HAVE_ARM_ARCH_V6,1, [Defined if ARM architecture is v6 or newer]) fi # # Check whether GCC inline assembler supports NEON instructions # AC_CACHE_CHECK([whether GCC inline assembler supports NEON instructions], [gcry_cv_gcc_inline_asm_neon], [if test "$mpi_cpu_arch" != "arm" ; then gcry_cv_gcc_inline_asm_neon="n/a" else gcry_cv_gcc_inline_asm_neon=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[__asm__( ".syntax unified\n\t" ".arm\n\t" ".fpu neon\n\t" "vld1.64 {%q0-%q1}, [%r0]!;\n\t" "vrev64.8 %q0, %q3;\n\t" "vadd.u64 %q0, %q1;\n\t" "vadd.s64 %d3, %d2, %d3;\n\t" ); ]])], [gcry_cv_gcc_inline_asm_neon=yes]) fi]) if test "$gcry_cv_gcc_inline_asm_neon" = "yes" ; then AC_DEFINE(HAVE_GCC_INLINE_ASM_NEON,1, [Defined if inline assembler supports NEON instructions]) fi # # Check whether GCC inline assembler supports AArch32 Crypto Extension instructions # AC_CACHE_CHECK([whether GCC inline assembler supports AArch32 Crypto Extension instructions], [gcry_cv_gcc_inline_asm_aarch32_crypto], [if test "$mpi_cpu_arch" != "arm" ; then gcry_cv_gcc_inline_asm_aarch32_crypto="n/a" else gcry_cv_gcc_inline_asm_aarch32_crypto=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[__asm__( ".syntax unified\n\t" ".arm\n\t" ".fpu crypto-neon-fp-armv8\n\t" "sha1h.32 q0, q0;\n\t" "sha1c.32 q0, q0, q0;\n\t" "sha1p.32 q0, q0, q0;\n\t" "sha1su0.32 q0, q0, q0;\n\t" "sha1su1.32 q0, q0;\n\t" "sha256h.32 q0, q0, q0;\n\t" "sha256h2.32 q0, q0, q0;\n\t" "sha1p.32 q0, q0, q0;\n\t" "sha256su0.32 q0, q0;\n\t" "sha256su1.32 q0, q0, q15;\n\t" "aese.8 q0, q0;\n\t" "aesd.8 q0, q0;\n\t" "aesmc.8 q0, q0;\n\t" "aesimc.8 q0, q0;\n\t" "vmull.p64 q0, d0, d0;\n\t" ); ]])], [gcry_cv_gcc_inline_asm_aarch32_crypto=yes]) fi]) if test "$gcry_cv_gcc_inline_asm_aarch32_crypto" = "yes" ; then AC_DEFINE(HAVE_GCC_INLINE_ASM_AARCH32_CRYPTO,1, [Defined if inline assembler supports AArch32 Crypto Extension instructions]) fi # # Check whether GCC inline assembler supports AArch64 NEON instructions # AC_CACHE_CHECK([whether GCC inline assembler supports AArch64 NEON instructions], [gcry_cv_gcc_inline_asm_aarch64_neon], [if test "$mpi_cpu_arch" != "aarch64" ; then gcry_cv_gcc_inline_asm_aarch64_neon="n/a" else gcry_cv_gcc_inline_asm_aarch64_neon=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[__asm__( ".cpu generic+simd\n\t" "mov w0, \#42;\n\t" "dup v0.8b, w0;\n\t" "ld4 {v0.8b,v1.8b,v2.8b,v3.8b},[x0],\#32;\n\t" ); ]])], [gcry_cv_gcc_inline_asm_aarch64_neon=yes]) fi]) if test "$gcry_cv_gcc_inline_asm_aarch64_neon" = "yes" ; then AC_DEFINE(HAVE_GCC_INLINE_ASM_AARCH64_NEON,1, [Defined if inline assembler supports AArch64 NEON instructions]) fi # # Check whether GCC inline assembler supports AArch64 Crypto Extension instructions # AC_CACHE_CHECK([whether GCC inline assembler supports AArch64 Crypto Extension instructions], [gcry_cv_gcc_inline_asm_aarch64_crypto], [if test "$mpi_cpu_arch" != "aarch64" ; then gcry_cv_gcc_inline_asm_aarch64_crypto="n/a" else gcry_cv_gcc_inline_asm_aarch64_crypto=no AC_COMPILE_IFELSE([AC_LANG_SOURCE( [[__asm__( ".cpu generic+simd+crypto\n\t" "mov w0, \#42;\n\t" "dup v0.8b, w0;\n\t" "ld4 {v0.8b,v1.8b,v2.8b,v3.8b},[x0],\#32;\n\t" "sha1h s0, s0;\n\t" "sha1c q0, s0, v0.4s;\n\t" "sha1p q0, s0, v0.4s;\n\t" "sha1su0 v0.4s, v0.4s, v0.4s;\n\t" "sha1su1 v0.4s, v0.4s;\n\t" "sha256h q0, q0, v0.4s;\n\t" "sha256h2 q0, q0, v0.4s;\n\t" "sha1p q0, s0, v0.4s;\n\t" "sha256su0 v0.4s, v0.4s;\n\t" "sha256su1 v0.4s, v0.4s, v31.4s;\n\t" "aese v0.16b, v0.16b;\n\t" "aesd v0.16b, v0.16b;\n\t" "aesmc v0.16b, v0.16b;\n\t" "aesimc v0.16b, v0.16b;\n\t" "pmull v0.1q, v0.1d, v31.1d;\n\t" "pmull2 v0.1q, v0.2d, v31.2d;\n\t" ); ]])], [gcry_cv_gcc_inline_asm_aarch64_crypto=yes]) fi]) if test "$gcry_cv_gcc_inline_asm_aarch64_crypto" = "yes" ; then AC_DEFINE(HAVE_GCC_INLINE_ASM_AARCH64_CRYPTO,1, [Defined if inline assembler supports AArch64 Crypto Extension instructions]) 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(syscall fcntl ftruncate flockfile) GNUPG_CHECK_MLOCK # # Replacement functions. # AC_REPLACE_FUNCS([getpid clock]) # -# Check wether it is necessary to link against libdl. +# Check whether 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 *-*-mingw32ce*) # WindowsCE random device. random_modules="w32ce" ;; *-*-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 # # Other defines # if test mym4_isgit = "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]) # CFLAGS mangling when using gcc. if test "$GCC" = yes; then CFLAGS="$CFLAGS -Wall" if test "$USE_MAINTAINER_MODE" = "yes"; then CFLAGS="$CFLAGS -Wcast-align -Wshadow -Wstrict-prototypes" CFLAGS="$CFLAGS -Wformat -Wno-format-y2k -Wformat-security" # If -Wno-missing-field-initializers is supported we can enable a # a bunch of really useful warnings. AC_MSG_CHECKING([if gcc supports -Wno-missing-field-initializers]) _gcc_cflags_save=$CFLAGS CFLAGS="-Wno-missing-field-initializers" 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 -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" 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 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_CONFIG_HOST) 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. #### ##################### # Check that requested feature can actually be used and define # ENABLE_foo_SUPPORT macros. if test x"$aesnisupport" = xyes ; then if test "$gcry_cv_gcc_inline_asm_ssse3" != "yes" ; then aesnisupport="no (unsupported by compiler)" fi fi if test x"$pclmulsupport" = xyes ; then if test "$gcry_cv_gcc_inline_asm_pclmul" != "yes" ; then pclmulsupport="no (unsupported by compiler)" fi fi if test x"$sse41support" = xyes ; then if test "$gcry_cv_gcc_inline_asm_sse41" != "yes" ; then sse41support="no (unsupported by compiler)" fi fi if test x"$avxsupport" = xyes ; then if test "$gcry_cv_gcc_inline_asm_avx" != "yes" ; then avxsupport="no (unsupported by compiler)" fi fi if test x"$avx2support" = xyes ; then if test "$gcry_cv_gcc_inline_asm_avx2" != "yes" ; then avx2support="no (unsupported by compiler)" fi fi if test x"$neonsupport" = xyes ; then if test "$gcry_cv_gcc_inline_asm_neon" != "yes" ; then if test "$gcry_cv_gcc_inline_asm_aarch64_neon" != "yes" ; then neonsupport="no (unsupported by compiler)" fi fi fi if test x"$armcryptosupport" = xyes ; then if test "$gcry_cv_gcc_inline_asm_aarch32_crypto" != "yes" ; then if test "$gcry_cv_gcc_inline_asm_aarch64_crypto" != "yes" ; then neonsupport="no (unsupported by compiler)" fi fi fi if test x"$aesnisupport" = xyes ; then AC_DEFINE(ENABLE_AESNI_SUPPORT, 1, [Enable support for Intel AES-NI instructions.]) fi if test x"$pclmulsupport" = xyes ; then AC_DEFINE(ENABLE_PCLMUL_SUPPORT, 1, [Enable support for Intel PCLMUL instructions.]) fi if test x"$sse41support" = xyes ; then AC_DEFINE(ENABLE_SSE41_SUPPORT, 1, [Enable support for Intel SSE4.1 instructions.]) fi if test x"$avxsupport" = xyes ; then AC_DEFINE(ENABLE_AVX_SUPPORT,1, [Enable support for Intel AVX instructions.]) fi if test x"$avx2support" = xyes ; then AC_DEFINE(ENABLE_AVX2_SUPPORT,1, [Enable support for Intel AVX2 instructions.]) fi if test x"$neonsupport" = xyes ; then AC_DEFINE(ENABLE_NEON_SUPPORT,1, [Enable support for ARM NEON instructions.]) fi if test x"$armcryptosupport" = xyes ; then AC_DEFINE(ENABLE_ARM_CRYPTO_SUPPORT,1, [Enable support for ARMv8 Crypto Extension instructions.]) fi if test x"$padlocksupport" = xyes ; then AC_DEFINE(ENABLE_PADLOCK_SUPPORT, 1, [Enable support for the PadLock engine.]) fi if test x"$drngsupport" = xyes ; then AC_DEFINE(ENABLE_DRNG_SUPPORT, 1, [Enable support for Intel DRNG (RDRAND instruction).]) fi # Define conditional sources and config.h symbols depending on the # selected ciphers, pubkey-ciphers, digests, kdfs, 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]) case "${host}" in x86_64-*-*) # Build with the assembly implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS arcfour-amd64.lo" ;; esac 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]) case "${host}" in x86_64-*-*) # Build with the assembly implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS blowfish-amd64.lo" ;; arm*-*-*) # Build with the assembly implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS blowfish-arm.lo" ;; esac 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]) case "${host}" in x86_64-*-*) # Build with the assembly implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS cast5-amd64.lo" ;; arm*-*-*) # Build with the assembly implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS cast5-arm.lo" ;; esac 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]) case "${host}" in x86_64-*-*) # Build with the assembly implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS des-amd64.lo" ;; esac 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]) case "${host}" in x86_64-*-*) # Build with the assembly implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS rijndael-amd64.lo" # Build with the SSSE3 implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS rijndael-ssse3-amd64.lo" GCRYPT_CIPHERS="$GCRYPT_CIPHERS rijndael-ssse3-amd64-asm.lo" ;; arm*-*-*) # Build with the assembly implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS rijndael-arm.lo" # Build with the ARMv8/AArch32 CE implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS rijndael-armv8-ce.lo" GCRYPT_CIPHERS="$GCRYPT_CIPHERS rijndael-armv8-aarch32-ce.lo" ;; aarch64-*-*) # Build with the assembly implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS rijndael-aarch64.lo" # Build with the ARMv8/AArch64 CE implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS rijndael-armv8-ce.lo" GCRYPT_CIPHERS="$GCRYPT_CIPHERS rijndael-armv8-aarch64-ce.lo" ;; esac case "$mpi_cpu_arch" in x86) # Build with the AES-NI implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS rijndael-aesni.lo" # Build with the Padlock implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS rijndael-padlock.lo" ;; esac 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]) case "${host}" in x86_64-*-*) # Build with the assembly implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS twofish-amd64.lo" if test x"$avx2support" = xyes ; then # Build with the AVX2 implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS twofish-avx2-amd64.lo" fi ;; arm*-*-*) # Build with the assembly implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS twofish-arm.lo" ;; aarch64-*-*) # Build with the assembly implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS twofish-aarch64.lo" ;; esac 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]) case "${host}" in x86_64-*-*) # Build with the SSE2 implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS serpent-sse2-amd64.lo" ;; esac if test x"$avx2support" = xyes ; then # Build with the AVX2 implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS serpent-avx2-amd64.lo" fi if test x"$neonsupport" = xyes ; then # Build with the NEON implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS serpent-armv7-neon.lo" fi 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]) case "${host}" in arm*-*-*) # Build with the assembly implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS camellia-arm.lo" ;; aarch64-*-*) # Build with the assembly implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS camellia-aarch64.lo" ;; esac if test x"$avxsupport" = xyes ; then if test x"$aesnisupport" = xyes ; then # Build with the AES-NI/AVX implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS camellia-aesni-avx-amd64.lo" fi fi if test x"$avx2support" = xyes ; then if test x"$aesnisupport" = xyes ; then # Build with the AES-NI/AVX2 implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS camellia-aesni-avx2-amd64.lo" fi fi fi LIST_MEMBER(idea, $enabled_ciphers) if test "$found" = "1" ; then GCRYPT_CIPHERS="$GCRYPT_CIPHERS idea.lo" AC_DEFINE(USE_IDEA, 1, [Defined if this module should be included]) fi LIST_MEMBER(salsa20, $enabled_ciphers) if test "$found" = "1" ; then GCRYPT_CIPHERS="$GCRYPT_CIPHERS salsa20.lo" AC_DEFINE(USE_SALSA20, 1, [Defined if this module should be included]) case "${host}" in x86_64-*-*) # Build with the assembly implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS salsa20-amd64.lo" ;; esac if test x"$neonsupport" = xyes ; then # Build with the NEON implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS salsa20-armv7-neon.lo" fi fi LIST_MEMBER(gost28147, $enabled_ciphers) if test "$found" = "1" ; then GCRYPT_CIPHERS="$GCRYPT_CIPHERS gost28147.lo" AC_DEFINE(USE_GOST28147, 1, [Defined if this module should be included]) fi LIST_MEMBER(chacha20, $enabled_ciphers) if test "$found" = "1" ; then GCRYPT_CIPHERS="$GCRYPT_CIPHERS chacha20.lo" AC_DEFINE(USE_CHACHA20, 1, [Defined if this module should be included]) case "${host}" in x86_64-*-*) # Build with the assembly implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS chacha20-sse2-amd64.lo" GCRYPT_CIPHERS="$GCRYPT_CIPHERS chacha20-ssse3-amd64.lo" GCRYPT_CIPHERS="$GCRYPT_CIPHERS chacha20-avx2-amd64.lo" ;; esac if test x"$neonsupport" = xyes ; then # Build with the NEON implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS chacha20-armv7-neon.lo" fi fi case "${host}" in x86_64-*-*) # Build with the assembly implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS poly1305-sse2-amd64.lo" GCRYPT_CIPHERS="$GCRYPT_CIPHERS poly1305-avx2-amd64.lo" ;; esac if test x"$neonsupport" = xyes ; then # Build with the NEON implementation GCRYPT_CIPHERS="$GCRYPT_CIPHERS poly1305-armv7-neon.lo" 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 ecc-curves.lo ecc-misc.lo \ ecc-ecdsa.lo ecc-eddsa.lo ecc-gost.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]) case "${host}" in i?86-*-* | x86_64-*-*) # Build with the assembly implementation GCRYPT_DIGESTS="$GCRYPT_DIGESTS crc-intel-pclmul.lo" ;; esac fi LIST_MEMBER(gostr3411-94, $enabled_digests) if test "$found" = "1" ; then # GOST R 34.11-94 internally uses GOST 28147-89 LIST_MEMBER(gost28147, $enabled_ciphers) if test "$found" = "1" ; then GCRYPT_DIGESTS="$GCRYPT_DIGESTS gostr3411-94.lo" AC_DEFINE(USE_GOST_R_3411_94, 1, [Defined if this module should be included]) fi fi LIST_MEMBER(stribog, $enabled_digests) if test "$found" = "1" ; then GCRYPT_DIGESTS="$GCRYPT_DIGESTS stribog.lo" AC_DEFINE(USE_GOST_R_3411_12, 1, [Defined if this module should be included]) fi LIST_MEMBER(md2, $enabled_digests) if test "$found" = "1" ; then GCRYPT_DIGESTS="$GCRYPT_DIGESTS md2.lo" AC_DEFINE(USE_MD2, 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(rmd160, $enabled_digests) if test "$found" = "1" ; then GCRYPT_DIGESTS="$GCRYPT_DIGESTS rmd160.lo" AC_DEFINE(USE_RMD160, 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]) case "${host}" in x86_64-*-*) # Build with the assembly implementation GCRYPT_DIGESTS="$GCRYPT_DIGESTS sha256-ssse3-amd64.lo" GCRYPT_DIGESTS="$GCRYPT_DIGESTS sha256-avx-amd64.lo" GCRYPT_DIGESTS="$GCRYPT_DIGESTS sha256-avx2-bmi2-amd64.lo" ;; arm*-*-*) # Build with the assembly implementation GCRYPT_DIGESTS="$GCRYPT_DIGESTS sha256-armv8-aarch32-ce.lo" ;; aarch64-*-*) # Build with the assembly implementation GCRYPT_DIGESTS="$GCRYPT_DIGESTS sha256-armv8-aarch64-ce.lo" ;; esac 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]) case "${host}" in x86_64-*-*) # Build with the assembly implementation GCRYPT_DIGESTS="$GCRYPT_DIGESTS sha512-ssse3-amd64.lo" GCRYPT_DIGESTS="$GCRYPT_DIGESTS sha512-avx-amd64.lo" GCRYPT_DIGESTS="$GCRYPT_DIGESTS sha512-avx2-bmi2-amd64.lo" ;; arm*-*-*) # Build with the assembly implementation GCRYPT_DIGESTS="$GCRYPT_DIGESTS sha512-arm.lo" ;; esac if test x"$neonsupport" = xyes ; then # Build with the NEON implementation GCRYPT_DIGESTS="$GCRYPT_DIGESTS sha512-armv7-neon.lo" fi fi LIST_MEMBER(sha3, $enabled_digests) if test "$found" = "1" ; then GCRYPT_DIGESTS="$GCRYPT_DIGESTS keccak.lo" AC_DEFINE(USE_SHA3, 1, [Defined if this module should be included]) case "${host}" in x86_64-*-*) # Build with the assembly implementation : ;; esac if test x"$neonsupport" = xyes ; then # Build with the NEON implementation GCRYPT_DIGESTS="$GCRYPT_DIGESTS keccak-armv7-neon.lo" fi 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]) case "${host}" in x86_64-*-*) # Build with the assembly implementation GCRYPT_DIGESTS="$GCRYPT_DIGESTS whirlpool-sse2-amd64.lo" ;; esac fi LIST_MEMBER(blake2, $enabled_digests) if test "$found" = "1" ; then GCRYPT_DIGESTS="$GCRYPT_DIGESTS blake2.lo" AC_DEFINE(USE_BLAKE2, 1, [Defined if this module should be included]) fi # SHA-1 needs to be included always for example because it is used by # random-csprng.c. GCRYPT_DIGESTS="$GCRYPT_DIGESTS sha1.lo" AC_DEFINE(USE_SHA1, 1, [Defined if this module should be included]) case "${host}" in x86_64-*-*) # Build with the assembly implementation GCRYPT_DIGESTS="$GCRYPT_DIGESTS sha1-ssse3-amd64.lo" GCRYPT_DIGESTS="$GCRYPT_DIGESTS sha1-avx-amd64.lo" GCRYPT_DIGESTS="$GCRYPT_DIGESTS sha1-avx-bmi2-amd64.lo" ;; arm*-*-*) # Build with the assembly implementation GCRYPT_DIGESTS="$GCRYPT_DIGESTS sha1-armv7-neon.lo" GCRYPT_DIGESTS="$GCRYPT_DIGESTS sha1-armv8-aarch32-ce.lo" ;; aarch64-*-*) # Build with the assembly implementation GCRYPT_DIGESTS="$GCRYPT_DIGESTS sha1-armv8-aarch64-ce.lo" ;; esac LIST_MEMBER(scrypt, $enabled_kdfs) if test "$found" = "1" ; then GCRYPT_KDFS="$GCRYPT_KDFS scrypt.lo" AC_DEFINE(USE_SCRYPT, 1, [Defined if this module should be included]) fi 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 LIST_MEMBER(w32ce, $random_modules) if test "$found" = "1" ; then GCRYPT_RANDOM="$GCRYPT_RANDOM rndw32ce.lo" AC_DEFINE(USE_RNDW32CE, 1, [Defined if the WindowsCE specific RNG should be used.]) fi AC_SUBST([GCRYPT_CIPHERS]) AC_SUBST([GCRYPT_PUBKEY_CIPHERS]) AC_SUBST([GCRYPT_DIGESTS]) AC_SUBST([GCRYPT_KDFS]) 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]) tmp=`echo "$enabled_kdfs" | tr ' ' : ` AC_DEFINE_UNQUOTED(LIBGCRYPT_KDFS, "$tmp", [List of available KDF algorithms]) # # Define conditional sources depending on the used hardware platform. # Note that all possible modules must also be listed in # src/Makefile.am (EXTRA_libgcrypt_la_SOURCES). # GCRYPT_HWF_MODULES= case "$mpi_cpu_arch" in x86) AC_DEFINE(HAVE_CPU_ARCH_X86, 1, [Defined for the x86 platforms]) GCRYPT_HWF_MODULES="hwf-x86.lo" ;; alpha) AC_DEFINE(HAVE_CPU_ARCH_ALPHA, 1, [Defined for Alpha platforms]) ;; sparc) AC_DEFINE(HAVE_CPU_ARCH_SPARC, 1, [Defined for SPARC platforms]) ;; mips) AC_DEFINE(HAVE_CPU_ARCH_MIPS, 1, [Defined for MIPS platforms]) ;; m68k) AC_DEFINE(HAVE_CPU_ARCH_M68K, 1, [Defined for M68k platforms]) ;; ppc) AC_DEFINE(HAVE_CPU_ARCH_PPC, 1, [Defined for PPC platforms]) ;; arm) AC_DEFINE(HAVE_CPU_ARCH_ARM, 1, [Defined for ARM platforms]) GCRYPT_HWF_MODULES="hwf-arm.lo" ;; aarch64) AC_DEFINE(HAVE_CPU_ARCH_ARM, 1, [Defined for ARM AArch64 platforms]) GCRYPT_HWF_MODULES="hwf-arm.lo" ;; esac AC_SUBST([GCRYPT_HWF_MODULES]) # # Option to disable building of doc file # build_doc=yes AC_ARG_ENABLE([doc], AC_HELP_STRING([--disable-doc], [do not build the documentation]), build_doc=$enableval, build_doc=yes) AM_CONDITIONAL([BUILD_DOC], [test "x$build_doc" != xno]) # # Provide information about the build. # BUILD_REVISION="mym4_revision" AC_SUBST(BUILD_REVISION) AC_DEFINE_UNQUOTED(BUILD_REVISION, "$BUILD_REVISION", [GIT commit id revision used to build this package]) changequote(,)dnl BUILD_FILEVERSION=`echo "$VERSION" | sed 's/\([0-9.]*\).*/\1./;s/\./,/g'` changequote([,])dnl BUILD_FILEVERSION="${BUILD_FILEVERSION}mym4_revision_dec" AC_SUBST(BUILD_FILEVERSION) AC_ARG_ENABLE([build-timestamp], AC_HELP_STRING([--enable-build-timestamp], [set an explicit build timestamp for reproducibility. (default is the current time in ISO-8601 format)]), [if test "$enableval" = "yes"; then BUILD_TIMESTAMP=`date -u +%Y-%m-%dT%H:%M+0000 2>/dev/null || date` else BUILD_TIMESTAMP="$enableval" fi], [BUILD_TIMESTAMP=""]) AC_SUBST(BUILD_TIMESTAMP) AC_DEFINE_UNQUOTED(BUILD_TIMESTAMP, "$BUILD_TIMESTAMP", [The time this package was configured for a build]) # And create the files. AC_CONFIG_FILES([ Makefile m4/Makefile compat/Makefile mpi/Makefile cipher/Makefile random/Makefile doc/Makefile src/Makefile src/gcrypt.h src/libgcrypt-config src/versioninfo.rc tests/Makefile ]) AC_CONFIG_FILES([tests/hashtest-256g], [chmod +x tests/hashtest-256g]) AC_CONFIG_FILES([tests/basic-disable-all-hwf], [chmod +x tests/basic-disable-all-hwf]) AC_OUTPUT detection_module="${GCRYPT_HWF_MODULES%.lo}" test -n "$detection_module" || detection_module="none" # Give some feedback GCRY_MSG_SHOW([],[]) GCRY_MSG_SHOW([Libgcrypt],[v${VERSION} has been configured as follows:]) GCRY_MSG_SHOW([],[]) GCRY_MSG_SHOW([Platform: ],[$PRINTABLE_OS_NAME ($host)]) GCRY_MSG_SHOW([Hardware detection module:],[$detection_module]) GCRY_MSG_WRAP([Enabled cipher algorithms:],[$enabled_ciphers]) GCRY_MSG_WRAP([Enabled digest algorithms:],[$enabled_digests]) GCRY_MSG_WRAP([Enabled kdf algorithms: ],[$enabled_kdfs]) GCRY_MSG_WRAP([Enabled pubkey algorithms:],[$enabled_pubkey_ciphers]) GCRY_MSG_SHOW([Random number generator: ],[$random]) GCRY_MSG_SHOW([Using linux capabilities: ],[$use_capabilities]) GCRY_MSG_SHOW([Try using Padlock crypto: ],[$padlocksupport]) GCRY_MSG_SHOW([Try using AES-NI crypto: ],[$aesnisupport]) GCRY_MSG_SHOW([Try using Intel PCLMUL: ],[$pclmulsupport]) GCRY_MSG_SHOW([Try using Intel SSE4.1: ],[$sse41support]) GCRY_MSG_SHOW([Try using DRNG (RDRAND): ],[$drngsupport]) GCRY_MSG_SHOW([Try using Intel AVX: ],[$avxsupport]) GCRY_MSG_SHOW([Try using Intel AVX2: ],[$avx2support]) GCRY_MSG_SHOW([Try using ARM NEON: ],[$neonsupport]) GCRY_MSG_SHOW([Try using ARMv8 crypto: ],[$armcryptosupport]) GCRY_MSG_SHOW([],[]) if test "x${gpg_config_script_warn}" != x; then cat < @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 definitions 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 compiler’s 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. If the used helper script does not match the target type you are building for a warning is printed and the string @code{libgcrypt} is appended to the variable @code{gpg_config_script_warn}. This macro searches for @command{libgcrypt-config} along the PATH. If you are cross-compiling, it is useful to set the environment variable @code{SYSROOT} to the top directory of your target. The macro will then first look for the helper program in the @file{bin} directory below that top directory. An absolute directory name must be used for @code{SYSROOT}. Finally, if the configure command line option @code{--with-libgcrypt-prefix} is used, only its value is used for the top directory below which the helper script is expected. @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. @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 initialized. */ 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 initialized. */ 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 initialized. */ /* Allocate a pool of 16k secure memory. This makes the secure memory available and also drops privileges where needed. Note that by using functions like gcry_xmalloc_secure and gcry_mpi_snew Libgcrypt may extend the secure memory pool with memory which lacks the property of not being swapped out to disk. */ 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 you use pthread and your applications forks and does not directly call exec (even calling stdio functions), all kind of problems may occur. Future versions of Libgcrypt will try to cleanup using pthread_atfork but even that may lead to problems. This is a common problem with almost all applications using pthread and fork. @item The function @code{gcry_check_version} must be called before any other function in the library. 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 @node Enabling FIPS mode @section How to enable the FIPS mode @cindex FIPS mode @cindex FIPS 140 @anchor{enabling 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} or by using the control command @code{GCRYCTL_SET_ENFORCED_FIPS_FLAG} before any other calls to libgcrypt. 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. @node Hardware features @section How to disable hardware features @cindex hardware features @anchor{hardware features} Libgcrypt makes use of certain hardware features. If the use of a feature is not desired it may be either be disabled by a program or globally using a configuration file. The currently supported features are @table @code @item padlock-rng @item padlock-aes @item padlock-sha @item padlock-mmul @item intel-cpu @item intel-fast-shld @item intel-bmi2 @item intel-ssse3 @item intel-pclmul @item intel-aesni @item intel-rdrand @item intel-avx @item intel-avx2 @item arm-neon @end table To disable a feature for all processes using Libgcrypt 1.6 or newer, create the file @file{/etc/gcrypt/hwf.deny} and put each feature not to be used on a single line. Empty lines, white space, and lines prefixed with a hash mark are ignored. The file should be world readable. To disable a feature specifically for a program that program must tell it Libgcrypt before before calling @code{gcry_check_version}. Example:@footnote{NB. Libgcrypt uses the RDRAND feature only as one source of entropy. A CPU with a broken RDRAND will thus not compromise of the random number generator} @example gcry_control (GCRYCTL_DISABLE_HWF, "intel-rdrand", NULL); @end example @noindent To print the list of active features you may use this command: @example mpicalc --print-config | grep ^hwflist: | tr : '\n' | tail -n +2 @end example @c ********************************************************** @c ******************* General **************************** @c ********************************************************** @node Generalities @chapter Generalities @menu * Controlling the library:: Controlling Libgcrypt's behavior. * 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 before @code{gcry_check_version}. 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 recommended. However, for some applications the extra quality random Libgcrypt tries to create is not justified and this option may help to get better performance. 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 random number generator related statistics to the library's logging stream. @item GCRYCTL_DUMP_MEMORY_STATS; Arguments: none This command dumps memory management related statistics to the library's logging stream. @item GCRYCTL_DUMP_SECMEM_STATS; Arguments: none This command dumps secure memory management 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 privileges 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 function @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_DISABLE_LOCKED_SECMEM; Arguments: none This command disables the use of the mlock call for secure memory. Disabling the use of mlock may for example be done if an encrypted swap space is in use. This command should be executed right after @code{gcry_check_version}. Note that by using functions like gcry_xmalloc_secure and gcry_mpi_snew Libgcrypt may extend the secure memory pool with memory which lacks the property of not being swapped out to disk (but will still be zeroed out on free). @item GCRYCTL_DISABLE_PRIV_DROP; Arguments: none This command sets a global flag to tell the secure memory subsystem that it shall not drop privileges after secure memory has been allocated. This command is commonly used right after @code{gcry_check_version} but may also be used right away at program startup. It won't have an effect after the secure memory pool has been initialized. WARNING: A process running setuid(root) is a severe security risk. Processes making use of Libgcrypt or other complex code should drop these extra privileges as soon as possible. If this command has been used the caller is responsible for dropping the privileges. @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 initial 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_CLOSE_RANDOM_DEVICE; Arguments: none Try to close the random device. If on Unix system you call fork(), the child process does no call exec(), and you do not intend to use Libgcrypt in the child, it might be useful to use this control code to close the inherited file descriptors of the random device. If Libgcrypt is later used again by the child, the device will be re-opened. On non-Unix systems this control code is ignored. @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 initialization is by calling gcry_check_version. @item GCRYCTL_INITIALIZATION_FINISHED; Arguments: none This command tells the library that the application has finished the initialization. @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 is obsolete since version 1.6. @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 initialization has been finished but not before a @code{gcry_check_version}. @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 initialization has been finished but not before a @code{gcry_check_version}. @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 initialization has been finished but not before a @code{gcry_check_version}. 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 @code{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 initialization. @item GCRYCTL_SET_ENFORCED_FIPS_FLAG; Arguments: none Running this command sets the internal flag that puts the library into the enforced FIPS mode during the FIPS mode initialization. This command does not affect the library if the library is not put into the FIPS mode and it must be used before any other libgcrypt library calls that initialize the library such as @code{gcry_check_version}. Note that Libgcrypt will reject an attempt to switch to the enforced fips mode during or after the initialization. @item GCRYCTL_SET_PREFERRED_RNG_TYPE; Arguments: int These are advisory commands to select a certain random number generator. They are only advisory because libraries may not know what an application actually wants or vice versa. Thus Libgcrypt employs a priority check to select the actually used RNG. If an applications selects a lower priority RNG but a library requests a higher priority RNG Libgcrypt will switch to the higher priority RNG. Applications and libraries should use these control codes before @code{gcry_check_version}. The available generators are: @table @code @item GCRY_RNG_TYPE_STANDARD A conservative standard generator based on the ``Continuously Seeded Pseudo Random Number Generator'' designed by Peter Gutmann. @item GCRY_RNG_TYPE_FIPS A deterministic random number generator conforming to he document ``NIST-Recommended Random Number Generator Based on ANSI X9.31 Appendix A.2.4 Using the 3-Key Triple DES and AES Algorithms'' (2005-01-31). This implementation uses the AES variant. @item GCRY_RNG_TYPE_SYSTEM A wrapper around the system's native RNG. On Unix system these are usually the /dev/random and /dev/urandom devices. @end table The default is @code{GCRY_RNG_TYPE_STANDARD} unless FIPS mode as been enabled; in which case @code{GCRY_RNG_TYPE_FIPS} is used and locked against further changes. @item GCRYCTL_GET_CURRENT_RNG_TYPE; Arguments: int * This command stores the type of the currently used RNG as an integer value at the provided address. @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. @item GCRYCTL_DISABLE_HWF; Arguments: const char *name Libgcrypt detects certain features of the CPU at startup time. For performance tests it is sometimes required not to use such a feature. This option may be used to disable a certain feature; i.e. Libgcrypt behaves as if this feature has not been detected. This call can be used several times to disable a set of features, or features may be given as a colon or comma delimited string. The special feature "all" can be used to disable all available features. Note that the detection code might be run if the feature has been disabled. This command must be used at initialization time; i.e. before calling @code{gcry_check_version}. @item GCRYCTL_REINIT_SYSCALL_CLAMP; Arguments: none Libgcrypt wraps blocking system calls with two functions calls (``system call clamp'') to give user land threading libraries a hook for re-scheduling. This works by reading the system call clamp from Libgpg-error at initialization time. However sometimes Libgcrypt needs to be initialized before the user land threading systems and at that point the system call clamp has not been registered with Libgpg-error and in turn Libgcrypt would not use them. The control code can be used to tell Libgcrypt that a system call clamp has now been registered with Libgpg-error and advised it to read the clamp again. Obviously this control code may only be used before a second thread is started in a process. @end table @end deftypefun @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_strsource} 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. It may be used only during initialization. @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 wait_dev_random Waiting to re-open a random device. @var{total} gives the number of seconds until the next try. @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. Using this function is in general not recommended because the standard Libgcrypt allocation functions are guaranteed to zeroize memory if needed. This function may be used only during initialization and may not be used in fips mode. @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{int (*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. The handler is called with 3 arguments: The first one is the pointer @var{cb_data} as set with this function, the second is the requested memory size and the last being a flag. If bit 0 of the flag is set, secure memory has been requested. The handler should either return true to indicate that Libgcrypt should try again allocating memory or return false to let Libgcrypt use its default fatal error handler. @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. * 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. @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. @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}. @item GCRY_CIPHER_SALSA20 @cindex Salsa20 This is the Salsa20 stream cipher. @item GCRY_CIPHER_SALSA20R12 @cindex Salsa20/12 This is the Salsa20/12 - reduced round version of Salsa20 stream cipher. @item GCRY_CIPHER_GOST28147 @cindex GOST 28147-89 The GOST 28147-89 cipher, defined in the respective GOST standard. Translation of this GOST into English is provided in the RFC-5830. @item GCRY_CIPHER_CHACHA20 @cindex ChaCha20 This is the ChaCha20 stream cipher. @end table @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 @item GCRY_CIPHER_MODE_CFB8 @cindex CFB, Cipher Feedback mode Cipher Feedback mode. For GCRY_CIPHER_MODE_CFB the shift size equals the block size of the cipher (e.g. for AES it is CFB-128). For GCRY_CIPHER_MODE_CFB8 the shift size is 8 bit but that variant is not yet available. @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. @item GCRY_CIPHER_MODE_AESWRAP @cindex AES-Wrap mode This mode is used to implement the AES-Wrap algorithm according to RFC-3394. It may be used with any 128 bit block length algorithm, however the specs require one of the 3 AES algorithms. These special conditions apply: If @code{gcry_cipher_setiv} has not been used the standard IV is used; if it has been used the lower 64 bit of the IV are used as the Alternative Initial Value. On encryption the provided output buffer must be 64 bit (8 byte) larger than the input buffer; in-place encryption is still allowed. On decryption the output buffer may be specified 64 bit (8 byte) shorter than then input buffer. As per specs the input length must be at least 128 bits and the length must be a multiple of 64 bits. @item GCRY_CIPHER_MODE_CCM @cindex CCM, Counter with CBC-MAC mode Counter with CBC-MAC mode is an Authenticated Encryption with Associated Data (AEAD) block cipher mode, which is specified in 'NIST Special Publication 800-38C' and RFC 3610. @item GCRY_CIPHER_MODE_GCM @cindex GCM, Galois/Counter Mode Galois/Counter Mode (GCM) is an Authenticated Encryption with Associated Data (AEAD) block cipher mode, which is specified in 'NIST Special Publication 800-38D'. @item GCRY_CIPHER_MODE_POLY1305 @cindex Poly1305 based AEAD mode with ChaCha20 This mode implements the Poly1305 Authenticated Encryption with Associated Data (AEAD) mode according to RFC-7539. This mode can be used with ChaCha20 stream cipher. @item GCRY_CIPHER_MODE_OCB @cindex OCB, OCB3 OCB is an Authenticated Encryption with Associated Data (AEAD) block cipher mode, which is specified in RFC-7253. Supported tag lengths are 128, 96, and 64 bit with the default being 128 bit. To switch to a different tag length @code{gcry_cipher_ctl} using the command @code{GCRYCTL_SET_TAGLEN} and the address of an @code{int} variable set to 12 (for 96 bit) or 8 (for 64 bit) provided for the @code{buffer} argument and @code{sizeof(int)} for @code{buflen}. Note that the use of @code{gcry_cipher_final} is required. @item GCRY_CIPHER_MODE_XTS @cindex XTS, XTS mode XEX-based tweaked-codebook mode with ciphertext stealing (XTS) mode is used to implement the AES-XTS as specified in IEEE 1619 Standard Architecture for Encrypted Shared Storage Media and NIST SP800-38E. The XTS mode requires doubling key-length, for example, using 512-bit key with AES-256 (@code{GCRY_CIPHER_AES256}). The 128-bit tweak value is feed to XTS mode as little-endian byte array using @code{gcry_cipher_setiv} function. When encrypting or decrypting, full-sized data unit buffers needs to be passed to @code{gcry_cipher_encrypt} or @code{gcry_cipher_decrypt}. The tweak value is automatically incremented after each call of @code{gcry_cipher_encrypt} and @code{gcry_cipher_decrypt}. Auto-increment allows avoiding need of setting IV between processing of sequential data units. @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. Poly1305 AEAD mode (@code{GCRY_CIPHER_MODE_POLY1305}) only works with ChaCha20 stream cipher. The block cipher modes (@code{GCRY_CIPHER_MODE_ECB}, @code{GCRY_CIPHER_MODE_CBC}, @code{GCRY_CIPHER_MODE_CFB}, @code{GCRY_CIPHER_MODE_OFB} and @code{GCRY_CIPHER_MODE_CTR}) will work with any block cipher algorithm. GCM mode (@code{GCRY_CIPHER_MODE_CCM}), CCM mode (@code{GCRY_CIPHER_MODE_GCM}), OCB mode (@code{GCRY_CIPHER_MODE_OCB}), and XTS mode (@code{GCRY_CIPHER_MODE_XTS}) will only work with block cipher algorithms which have the block size of 16 bytes. 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}. It also zeroises all sensitive information associated with this cipher handle. @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} (in bytes) 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} bytes and copied to internal data structures. The function checks that the IV matches the requirement of the selected algorithm and mode. This function is also used by AEAD modes and with Salsa20 and ChaCha20 stream ciphers to set or update the required nonce. In these cases it needs to be called after setting the key. @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} bytes 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 Authenticated Encryption with Associated Data (AEAD) block cipher modes require the handling of the authentication tag and the additional authenticated data, which can be done by using the following functions: @deftypefun gcry_error_t gcry_cipher_authenticate (gcry_cipher_hd_t @var{h}, const void *@var{abuf}, size_t @var{abuflen}) Process the buffer @var{abuf} of length @var{abuflen} as the additional authenticated data (AAD) for AEAD cipher modes. @end deftypefun @deftypefun {gcry_error_t} gcry_cipher_gettag @ (@w{gcry_cipher_hd_t @var{h}}, @ @w{void *@var{tag}}, @w{size_t @var{taglen}}) This function is used to read the authentication tag after encryption. The function finalizes and outputs the authentication tag to the buffer @var{tag} of length @var{taglen} bytes. Depending on the used mode certain restrictions for @var{taglen} are enforced: For GCM @var{taglen} must be at least 16 or one of the allowed truncated lengths (4, 8, 12, 13, 14, or 15). @end deftypefun @deftypefun {gcry_error_t} gcry_cipher_checktag @ (@w{gcry_cipher_hd_t @var{h}}, @ @w{const void *@var{tag}}, @w{size_t @var{taglen}}) Check the authentication tag after decryption. The authentication tag is passed as the buffer @var{tag} of length @var{taglen} bytes and compared to internal authentication tag computed during decryption. Error code @code{GPG_ERR_CHECKSUM} is returned if the authentication tag in the buffer @var{tag} does not match the authentication tag calculated during decryption. Depending on the used mode certain restrictions for @var{taglen} are enforced: For GCM @var{taglen} must either be 16 or one of the allowed truncated lengths (4, 8, 12, 13, 14, or 15). @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} of 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. Some encryption modes require that @code{gcry_cipher_final} is used before the final data chunk is passed to this function. 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. Some encryption modes require that @code{gcry_cipher_final} is used before the final data chunk is passed to this function. The function returns @code{0} on success or an error code. @end deftypefun The OCB mode features integrated padding and must thus be told about the end of the input data. This is done with: @deftypefun gcry_error_t gcry_cipher_final (gcry_cipher_hd_t @var{h}) Set a flag in the context to tell the encrypt and decrypt functions that their next call will provide the last chunk of data. Only the first call to this function has an effect and only for modes which support it. Checking the error is in general not necessary. This is implemented as a macro. @end deftypefun OpenPGP (as defined in RFC-4880) 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. @c begin constants for gcry_cipher_info @table @code @item GCRYCTL_GET_TAGLEN: Return the length of the tag for an AE algorithm mode. An error is returned for modes which do not support a tag. @var{buffer} must be given as NULL. On success the result is stored @var{nbytes}. The taglen is returned in bytes. @end table @c end constants for gcry_cipher_info @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. Note that it is usually better to use the convenience function @code{gcry_cipher_get_algo_keylen}. @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. Note that it is usually better to use the convenience function @code{gcry_cipher_get_algo_blklen}. @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 size_t gcry_cipher_get_algo_keylen (@var{algo}) This function returns length of the key for algorithm @var{algo}. If the algorithm supports multiple key lengths, the maximum supported key length is returned. On error @code{0} is returned. The key length is returned as number of octets. This is a convenience functions which should be preferred over @code{gcry_cipher_algo_info} because it allows for proper type checking. @end deftypefun @c end gcry_cipher_get_algo_keylen @deftypefun size_t gcry_cipher_get_algo_blklen (int @var{algo}) This functions returns the block-length of the algorithm @var{algo} counted in octets. On error @code{0} is returned. This is a convenience functions which should be preferred over @code{gcry_cipher_algo_info} because it allows for proper type checking. @end deftypefun @c end gcry_cipher_get_algo_blklen @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. * Cryptographic Functions:: Functions for performing the cryptographic actions. * General public-key related Functions:: General functions, not implementing any cryptography. @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 @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 @anchor{ecc_keyparam} @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 = dG}. @item d-mpi The private key @math{d} @end table All point values are encoded in standard format; Libgcrypt does in general only support uncompressed points, thus the first byte needs to be @code{0x04}. However ``EdDSA'' describes its own compression scheme which is used by default; the non-standard first byte @code{0x40} may optionally be used to explicit flag the use of the algorithm’s native compression method. 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 Note that @var{q-point} is optional for a private key. 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 Cryptographic Functions @section Cryptographic Functions @noindent Some functions operating on S-expressions support `flags' to influence the operation. These flags have to be listed in a sub-S-expression named `flags'. Flag names are case-sensitive. The following flags are known: @table @code @item comp @itemx nocomp @cindex comp @cindex nocomp If supported by the algorithm and curve the @code{comp} flag requests that points are returned in compact (compressed) representation. The @code{nocomp} flag requests that points are returned with full coordinates. The default depends on the the algorithm and curve. The compact representation requires a small overhead before a point can be used but halves the size of a to be conveyed public key. If @code{comp} is used with the ``EdDSA'' algorithm the key generation prefix the public key with a @code{0x40} byte. @item pkcs1 @cindex PKCS1 Use PKCS#1 block type 2 padding for encryption, block type 1 padding for signing. @item oaep @cindex OAEP Use RSA-OAEP padding for encryption. @item pss @cindex PSS Use RSA-PSS padding for signing. @item eddsa @cindex EdDSA Use the EdDSA scheme signing instead of the default ECDSA algorithm. Note that the EdDSA uses a special form of the public key. @item rfc6979 @cindex RFC6979 For DSA and ECDSA use a deterministic scheme for the k parameter. @item no-blinding @cindex 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. @item param @cindex param For ECC key generation also return the domain parameters. For ECC signing and verification override default parameters by provided domain parameters of the public or private key. @item transient-key @cindex transient-key This flag is only meaningful for RSA, DSA, and ECC key generation. If given the 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 or per-message and do not require full cryptographic strength. @item no-keytest @cindex no-keytest This flag skips internal failsafe tests to assert that a generated key is properly working. It currently has an effect only for standard ECC key generation. It is mostly useful along with transient-key to achieve fastest ECC key generation. @item use-x931 @cindex X9.31 Force the use of the ANSI X9.31 key generation algorithm instead of the default algorithm. This flag is only meaningful for RSA key generation and usually not required. Note that this algorithm is implicitly used if either @code{derive-parms} is given or Libgcrypt is in FIPS mode. @item use-fips186 @cindex FIPS 186 Force the use of the FIPS 186 key generation algorithm instead of the default algorithm. This flag is only meaningful for DSA and usually not required. Note that this algorithm is implicitly used if either @code{derive-parms} is given or Libgcrypt is in FIPS mode. As of now FIPS 186-2 is implemented; after the approval of FIPS 186-3 the code will be changed to implement 186-3. @item use-fips186-2 @cindex FIPS 186-2 Force the use of the FIPS 186-2 key generation algorithm instead of the default algorithm. This algorithm is slightly different from FIPS 186-3 and allows only 1024 bit keys. This flag is only meaningful for DSA and only required for FIPS testing backward compatibility. @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 RSA based 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 This function does not remove padding from the data by default. To let Libgcrypt remove padding, give a hint in `flags' telling which padding method was used when encrypting: @example (flags @var{padding-method}) @end example @noindent Currently @var{padding-method} is either @code{pkcs1} for PKCS#1 block type 2 padding, or @code{oaep} for RSA-OAEP padding. @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 "sha256" or "sha1". 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 For DSA the input data is expected in this format: @example (data (flags raw) (value @var{mpi})) @end example @noindent Here, the data to be signed is directly given as an @var{MPI}. It is expect that this MPI is the the hash value. For the standard DSA using a MPI is not a problem in regard to leading zeroes because the hash value is directly used as an MPI. For better standard conformance it would be better to explicit use a memory string (like with pkcs1) but that is currently not supported. However, for deterministic DSA as specified in RFC6979 this can't be used. Instead the following input is expected. @example (data (flags rfc6979) (hash @var{hash-algo} @var{block})) @end example Note that the provided hash-algo is used for the internal HMAC; it should match the hash-algo used to create @var{block}. @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"; for ECDSA signing, the same format is used with "ecdsa" replacing "dsa". For the EdDSA algorithm (cf. Ed25515) the required input parameters are: @example (data (flags eddsa) (hash-algo sha512) (value @var{message})) @end example Note that the @var{message} may be of any length; hashing is part of the algorithm. Using a large data block for @var{message} is not suggested; in that case the used protocol should better require that a hash of the message is used as input to the EdDSA algorithm. @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{GCRY_ERR_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)}. This function is not thread safe and should thus be used before any other threads are started. @end table @end deftypefun @c end gcry_pk_ctl @noindent 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} to create an 2048 bit RSA key: @example (genkey (rsa (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. Note that the S-expression syntax requires that a number is prefixed with its string length; thus the @code{4:} in the above example. @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 @var{value} This is only used with RSA to give a hint for the public exponent. The @var{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 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 @var{n} This is only meanigful for DSA keys. If it is given the DSA key is generated with a Q parameyer of size @var{n} bits. 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 domain @var{list} 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})))) @end example @code{nbits} and @code{qbits} may not be specified because they are derived from the domain parameters. @item derive-parms @var{list} This is currently only implemented for RSA and DSA keys. It is not allowed to use this together with a @code{domain} specification. If given, it is used to derive the keys using the given parameters. If given for an RSA key the X9.31 key generation algorithm is used even if libgcrypt is not in FIPS mode. If given for a DSA key, the FIPS 186 algorithm is used even if libgcrypt is not in FIPS mode. @example (genkey (rsa (nbits 4:1024) (rsa-use-e 1:3) (derive-parms (Xp1 #1A1916DDB29B4EB7EB6732E128#) (Xp2 #192E8AAC41C576C822D93EA433#) (Xp #D8CD81F035EC57EFE822955149D3BFF70C53520D 769D6D76646C7A792E16EBD89FE6FC5B605A6493 39DFC925A86A4C6D150B71B9EEA02D68885F5009 B98BD984#) (Xq1 #1A5CF72EE770DE50CB09ACCEA9#) (Xq2 #134E4CAA16D2350A21D775C404#) (Xq #CC1092495D867E64065DEE3E7955F2EBC7D47A2D 7C9953388F97DDDC3E1CA19C35CA659EDC2FC325 6D29C2627479C086A699A49C4C9CEE7EF7BD1B34 321DE34A#)))) @end example @example (genkey (dsa (nbits 4:1024) (derive-parms (seed @var{seed-mpi})))) @end example @item flags @var{flaglist} This is preferred way to define flags. @var{flaglist} may contain any number of flags. See above for a specification of these flags. Here is an example on how to create a key using curve Ed25519 with the ECDSA signature algorithm. Note that the use of ECDSA with that curve is in general not recommended. @example (genkey (ecc (flags transient-key))) @end example @item transient-key @itemx use-x931 @itemx use-fips186 @itemx use-fips186-2 These are deprecated ways to set a flag with that name; see above for a description of each flag. @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 Here are two examples; the first for Elgamal and the second for elliptic curve key generation: @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 @example (key-data (public-key (ecc (curve Ed25519) (flags eddsa) (q @var{q-value}))) (private-key (ecc (curve Ed25519) (flags eddsa) (q @var{q-value}) (d @var{d-value})))) @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 and only available if the key generation algorithm provides them. @end deftypefun @c end gcry_pk_genkey @noindent Future versions of Libgcrypt will have extended versions of the public key interfaced which will take an additional context to allow for pre-computations, special operations, and other optimization. As a first step a new function is introduced to help using the ECC algorithms in new ways: @deftypefun gcry_error_t gcry_pubkey_get_sexp (@w{gcry_sexp_t *@var{r_sexp}}, @ @w{int @var{mode}}, @w{gcry_ctx_t @var{ctx}}) Return an S-expression representing the context @var{ctx}. Depending on the state of that context, the S-expression may either be a public key, a private key or any other object used with public key operations. On success 0 is returned and a new S-expression is stored at @var{r_sexp}; on error an error code is returned and NULL is stored at @var{r_sexp}. @var{mode} must be one of: @table @code @item 0 Decide what to return depending on the context. For example if the private key parameter is available a private key is returned, if not a public key is returned. @item GCRY_PK_GET_PUBKEY Return the public key even if the context has the private key parameter. @item GCRY_PK_GET_SECKEY Return the private key or the error @code{GPG_ERR_NO_SECKEY} if it is not possible. @end table As of now this function supports only certain ECC operations because a context object is right now only defined for ECC. Over time this function will be extended to cover more algorithms. @end deftypefun @c end gcry_pubkey_get_sexp @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 HMAC 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. * 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 SHA3-224, SHA3-256, SHA3-384, SHA3-512, SHAKE128, SHAKE256 @cindex RIPE-MD-160 @cindex MD2, MD4, MD5 @cindex TIGER, TIGER1, TIGER2 @cindex HAVAL @cindex Whirlpool @cindex BLAKE2b-512, BLAKE2b-384, BLAKE2b-256, BLAKE2b-160 @cindex BLAKE2s-256, BLAKE2s-224, BLAKE2s-160, BLAKE2s-128 @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. Note that SHA-1 begins to show some weaknesses and it is suggested to fade out its use if strong cryptographic properties are required. @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. This algorithm share a lot of design properties with SHA-1 and thus it is advisable not to use it for new protocols. @item GCRY_MD_MD5 This is the well known MD5 algorithm, which yields a message digest of 16 bytes. Note that the MD5 algorithm has severe weaknesses, for example it is easy to compute two messages yielding the same hash (collision attack). The use of this algorithm is only justified for non-cryptographic application. @item GCRY_MD_MD4 This is the MD4 algorithm, which yields a message digest of 16 bytes. This algorithm has severe weaknesses and should not be used. @item GCRY_MD_MD2 This is an reserved identifier for MD-2; there is no implementation yet. This algorithm has severe weaknesses and should not be used. @item GCRY_MD_TIGER This is the TIGER/192 algorithm which yields a message digest of 24 bytes. Actually this is a variant of TIGER with a different output print order as used by GnuPG up to version 1.3.2. @item GCRY_MD_TIGER1 This is the TIGER variant as used by the NESSIE project. It uses the most commonly used output print order. @item GCRY_MD_TIGER2 This is another variant of TIGER with a different padding scheme. @item GCRY_MD_HAVAL This is an reserved value 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_SHA3_224 This is the SHA3-224 algorithm which yields a message digest of 28 bytes. See FIPS 202 for the specification. @item GCRY_MD_SHA3_256 This is the SHA3-256 algorithm which yields a message digest of 32 bytes. See FIPS 202 for the specification. @item GCRY_MD_SHA3_384 This is the SHA3-384 algorithm which yields a message digest of 48 bytes. See FIPS 202 for the specification. @item GCRY_MD_SHA3_512 This is the SHA3-384 algorithm which yields a message digest of 64 bytes. See FIPS 202 for the specification. @item GCRY_MD_SHAKE128 This is the SHAKE128 extendable-output function (XOF) algorithm with 128 bit security strength. See FIPS 202 for the specification. @item GCRY_MD_SHAKE256 This is the SHAKE256 extendable-output function (XOF) algorithm with 256 bit security strength. See FIPS 202 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. Note that this is not a hash algorithm in the cryptographic sense. @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. Note that this is not a hash algorithm in the cryptographic sense. @item GCRY_MD_CRC24_RFC2440 This is the OpenPGP cyclic redundancy check function. It yields an output of 3 bytes. Note that this is not a hash algorithm in the cryptographic sense. @item GCRY_MD_WHIRLPOOL This is the Whirlpool algorithm which yields a message digest of 64 bytes. @item GCRY_MD_GOSTR3411_94 This is the hash algorithm described in GOST R 34.11-94 which yields a message digest of 32 bytes. @item GCRY_MD_STRIBOG256 This is the 256-bit version of hash algorithm described in GOST R 34.11-2012 which yields a message digest of 32 bytes. @item GCRY_MD_STRIBOG512 This is the 512-bit version of hash algorithm described in GOST R 34.11-2012 which yields a message digest of 64 bytes. @item GCRY_MD_BLAKE2B_512 This is the BLAKE2b-512 algorithm which yields a message digest of 64 bytes. See RFC 7693 for the specification. @item GCRY_MD_BLAKE2B_384 This is the BLAKE2b-384 algorithm which yields a message digest of 48 bytes. See RFC 7693 for the specification. @item GCRY_MD_BLAKE2B_256 This is the BLAKE2b-256 algorithm which yields a message digest of 32 bytes. See RFC 7693 for the specification. @item GCRY_MD_BLAKE2B_160 This is the BLAKE2b-160 algorithm which yields a message digest of 20 bytes. See RFC 7693 for the specification. @item GCRY_MD_BLAKE2S_256 This is the BLAKE2s-256 algorithm which yields a message digest of 32 bytes. See RFC 7693 for the specification. @item GCRY_MD_BLAKE2S_224 This is the BLAKE2s-224 algorithm which yields a message digest of 28 bytes. See RFC 7693 for the specification. @item GCRY_MD_BLAKE2S_160 This is the BLAKE2s-160 algorithm which yields a message digest of 20 bytes. See RFC 7693 for the specification. @item GCRY_MD_BLAKE2S_128 This is the BLAKE2s-128 algorithm which yields a message digest of 16 bytes. See RFC 7693 for the specification. @end table @c end table of hash algorithms @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 and that algorithm is not an extendable-output function. 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}. @item GCRY_MD_FLAG_BUGEMU1 @cindex bug emulation Versions of Libgcrypt before 1.6.0 had a bug in the Whirlpool code which led to a wrong result for certain input sizes and write patterns. Using this flag emulates that bug. This may for example be useful for applications which use Whirlpool as part of their key generation. It is strongly suggested to use this flag only if really needed and if possible to the data should be re-processed using the regular Whirlpool algorithm. Note that this flag works for the entire hash context. If needed arises it may be used to enable bug emulation for other hash algorithms. Thus you should not use this flag for a multi-algorithm hash context. @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 or BLAKE2 keyed hash, set the MAC key to the value of @var{key} of length @var{keylen} bytes. For HMAC, there is no restriction on the length of the key. For keyed BLAKE2b hash, length of the key must be 64 bytes or less. For keyed BLAKE2s hash, length of the key must be 32 bytes or less. @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. The function also zeroises all sensitive information associated with this handle. @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. If this function is used after the context has been finalized, it will keep on pushing the data through the algorithm specific transform function and change the context; however the results are not meaningful and this feature is only available to mitigate timing attacks. @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} and @code{gcry_md_extract} do this implicitly. After this has been done no further updates (by means of @code{gcry_md_write} or @code{gcry_md_putc} should be done; However, to mitigate timing attacks it is sometimes useful to keep on updating the context after having stored away the actual digest. 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 reset-ed (using @code{gcry_md_close} or @code{gcry_md_reset} or it has been updated as a mitigation measure against timing attacks. @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 The way to read output of extendable-output function is by using the function: @deftypefun gpg_err_code_t gcry_md_extract (gcry_md_hd_t @var{h}, @ int @var{algo}, void *@var{buffer}, size_t @var{length}) @code{gcry_mac_read} returns output from extendable-output function. This function may be used as often as required to generate more output byte stream from the algorithm. Function extracts the new output bytes to @var{buffer} of the length @var{length}. Buffer will be fully populated with new output. @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 non-zero value if the requested algorithm has not been enabled. @end deftypefun Because it is often necessary to get the message digest of blocks of memory, two fast convenience function are available for this task: @deftypefun gpg_err_code_t gcry_md_hash_buffers ( @ @w{int @var{algo}}, @w{unsigned int @var{flags}}, @ @w{void *@var{digest}}, @ @w{const gcry_buffer_t *@var{iov}}, @w{int @var{iovcnt}} ) @code{gcry_md_hash_buffers} is a shortcut function to calculate a message digest from several buffers. This function does not require a context and immediately returns the message digest of the data described by @var{iov} and @var{iovcnt}. @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}. @var{iov} is an array of buffer descriptions with @var{iovcnt} items. The caller should zero out the structures in this array and for each array item set the fields @code{.data} to the address of the data to be hashed, @code{.len} to number of bytes to be hashed. If @var{.off} is also set, the data is taken starting at @var{.off} bytes from the begin of the buffer. The field @code{.size} is not used. The only supported flag value for @var{flags} is @var{GCRY_MD_FLAG_HMAC} which turns this function into a HMAC function; the first item in @var{iov} is then used as the key. On success the function returns 0 and stores the resulting hash or MAC at @var{digest}. @end deftypefun @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 in contrast to @code{gcry_md_hash_buffers} 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 files named @file{dbgmd-.} 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 @c ********************************************************** @c ******************* MAC Functions ********************** @c ********************************************************** @node Message Authentication Codes @chapter Message Authentication Codes Libgcrypt provides an easy and consistent to use interface for generating Message Authentication Codes (MAC). MAC generation is buffered and interface similar to the one used with hash algorithms. The programming model follows an open/process/close paradigm and is in that similar to other building blocks provided by Libgcrypt. @menu * Available MAC algorithms:: List of MAC algorithms supported by the library. * Working with MAC algorithms:: List of functions related to MAC algorithms. @end menu @node Available MAC algorithms @section Available MAC algorithms @c begin table of MAC algorithms @cindex HMAC-SHA-1 @cindex HMAC-SHA-224, HMAC-SHA-256, HMAC-SHA-384, HMAC-SHA-512 @cindex HMAC-SHA3-224, HMAC-SHA3-256, HMAC-SHA3-384, HMAC-SHA3-512 @cindex HMAC-RIPE-MD-160 @cindex HMAC-MD2, HMAC-MD4, HMAC-MD5 @cindex HMAC-TIGER1 @cindex HMAC-Whirlpool @cindex HMAC-Stribog-256, HMAC-Stribog-512 @cindex HMAC-GOSTR-3411-94 @table @code @item GCRY_MAC_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_MAC_HMAC_SHA256 This is keyed-hash message authentication code (HMAC) message authentication algorithm based on the SHA-256 hash algorithm. @item GCRY_MAC_HMAC_SHA224 This is HMAC message authentication algorithm based on the SHA-224 hash algorithm. @item GCRY_MAC_HMAC_SHA512 This is HMAC message authentication algorithm based on the SHA-512 hash algorithm. @item GCRY_MAC_HMAC_SHA384 This is HMAC message authentication algorithm based on the SHA-384 hash algorithm. @item GCRY_MAC_HMAC_SHA3_256 This is HMAC message authentication algorithm based on the SHA3-384 hash algorithm. @item GCRY_MAC_HMAC_SHA3_224 This is HMAC message authentication algorithm based on the SHA3-224 hash algorithm. @item GCRY_MAC_HMAC_SHA3_512 This is HMAC message authentication algorithm based on the SHA3-512 hash algorithm. @item GCRY_MAC_HMAC_SHA3_384 This is HMAC message authentication algorithm based on the SHA3-384 hash algorithm. @item GCRY_MAC_HMAC_SHA1 This is HMAC message authentication algorithm based on the SHA-1 hash algorithm. @item GCRY_MAC_HMAC_MD5 This is HMAC message authentication algorithm based on the MD5 hash algorithm. @item GCRY_MAC_HMAC_MD4 This is HMAC message authentication algorithm based on the MD4 hash algorithm. @item GCRY_MAC_HMAC_RMD160 This is HMAC message authentication algorithm based on the RIPE-MD-160 hash algorithm. @item GCRY_MAC_HMAC_WHIRLPOOL This is HMAC message authentication algorithm based on the WHIRLPOOL hash algorithm. @item GCRY_MAC_HMAC_GOSTR3411_94 This is HMAC message authentication algorithm based on the GOST R 34.11-94 hash algorithm. @item GCRY_MAC_HMAC_STRIBOG256 This is HMAC message authentication algorithm based on the 256-bit hash algorithm described in GOST R 34.11-2012. @item GCRY_MAC_HMAC_STRIBOG512 This is HMAC message authentication algorithm based on the 512-bit hash algorithm described in GOST R 34.11-2012. @item GCRY_MAC_CMAC_AES This is CMAC (Cipher-based MAC) message authentication algorithm based on the AES block cipher algorithm. @item GCRY_MAC_CMAC_3DES This is CMAC message authentication algorithm based on the three-key EDE Triple-DES block cipher algorithm. @item GCRY_MAC_CMAC_CAMELLIA This is CMAC message authentication algorithm based on the Camellia block cipher algorithm. @item GCRY_MAC_CMAC_CAST5 This is CMAC message authentication algorithm based on the CAST128-5 block cipher algorithm. @item GCRY_MAC_CMAC_BLOWFISH This is CMAC message authentication algorithm based on the Blowfish block cipher algorithm. @item GCRY_MAC_CMAC_TWOFISH This is CMAC message authentication algorithm based on the Twofish block cipher algorithm. @item GCRY_MAC_CMAC_SERPENT This is CMAC message authentication algorithm based on the Serpent block cipher algorithm. @item GCRY_MAC_CMAC_SEED This is CMAC message authentication algorithm based on the SEED block cipher algorithm. @item GCRY_MAC_CMAC_RFC2268 This is CMAC message authentication algorithm based on the Ron's Cipher 2 block cipher algorithm. @item GCRY_MAC_CMAC_IDEA This is CMAC message authentication algorithm based on the IDEA block cipher algorithm. @item GCRY_MAC_CMAC_GOST28147 This is CMAC message authentication algorithm based on the GOST 28147-89 block cipher algorithm. @item GCRY_MAC_GMAC_AES This is GMAC (GCM mode based MAC) message authentication algorithm based on the AES block cipher algorithm. @item GCRY_MAC_GMAC_CAMELLIA This is GMAC message authentication algorithm based on the Camellia block cipher algorithm. @item GCRY_MAC_GMAC_TWOFISH This is GMAC message authentication algorithm based on the Twofish block cipher algorithm. @item GCRY_MAC_GMAC_SERPENT This is GMAC message authentication algorithm based on the Serpent block cipher algorithm. @item GCRY_MAC_GMAC_SEED This is GMAC message authentication algorithm based on the SEED block cipher algorithm. @item GCRY_MAC_POLY1305 This is plain Poly1305 message authentication algorithm, used with one-time key. @item GCRY_MAC_POLY1305_AES This is Poly1305-AES message authentication algorithm, used with key and one-time nonce. @item GCRY_MAC_POLY1305_CAMELLIA This is Poly1305-Camellia message authentication algorithm, used with key and one-time nonce. @item GCRY_MAC_POLY1305_TWOFISH This is Poly1305-Twofish message authentication algorithm, used with key and one-time nonce. @item GCRY_MAC_POLY1305_SERPENT This is Poly1305-Serpent message authentication algorithm, used with key and one-time nonce. @item GCRY_MAC_POLY1305_SEED This is Poly1305-SEED message authentication algorithm, used with key and one-time nonce. @end table @c end table of MAC algorithms @node Working with MAC algorithms @section Working with MAC algorithms To use most of these function it is necessary to create a context; this is done using: @deftypefun gcry_error_t gcry_mac_open (gcry_mac_hd_t *@var{hd}, int @var{algo}, unsigned int @var{flags}, gcry_ctx_t @var{ctx}) Create a MAC object for algorithm @var{algo}. @var{flags} may be given as an bitwise OR of constants described below. @var{hd} is guaranteed to either receive a valid handle or NULL. @var{ctx} is context object to associate MAC object with. @var{ctx} maybe set to NULL. For a list of supported algorithms, see @xref{Available MAC algorithms}. The flags allowed for @var{mode} are: @c begin table of MAC flags @table @code @item GCRY_MAC_FLAG_SECURE Allocate all buffers and the resulting MAC in "secure memory". Use this if the MAC data is highly confidential. @end table @c begin table of MAC flags @end deftypefun @c end function gcry_mac_open In order to use a handle for performing MAC algorithm operations, a `key' has to be set first: @deftypefun gcry_error_t gcry_mac_setkey (gcry_mac_hd_t @var{h}, const void *@var{key}, size_t @var{keylen}) Set the MAC key to the value of @var{key} of length @var{keylen} bytes. With HMAC algorithms, there is no restriction on the length of the key. With CMAC algorithms, the length of the key is restricted to those supported by the underlying block cipher. @end deftypefun GMAC algorithms and Poly1305-with-cipher algorithms need initialization vector to be set, which can be performed with function: @deftypefun gcry_error_t gcry_mac_setiv (gcry_mac_hd_t @var{h}, const void *@var{iv}, size_t @var{ivlen}) Set the IV to the value of @var{iv} of length @var{ivlen} bytes. @end deftypefun After you are done with the MAC calculation, you should release the resources by using: @deftypefun void gcry_mac_close (gcry_mac_hd_t @var{h}) Release all resources of MAC context @var{h}. @var{h} should not be used after a call to this function. A @code{NULL} passed as @var{h} is ignored. The function also clears all sensitive information associated with this handle. @end deftypefun Often you have to do several MAC operations using the same algorithm. To avoid the overhead of creating and releasing context, a reset function is provided: @deftypefun gcry_error_t gcry_mac_reset (gcry_mac_hd_t @var{h}) Reset the current context to its initial state. This is effectively identical to a close followed by an open and setting same key. Note that gcry_mac_reset is implemented as a macro. @end deftypefun Now that we have prepared everything to calculate MAC, it is time to see how it is actually done. @deftypefun gcry_error_t gcry_mac_write (gcry_mac_hd_t @var{h}, const void *@var{buffer}, size_t @var{length}) Pass @var{length} bytes of the data in @var{buffer} to the MAC object with handle @var{h} to update the MAC values. If this function is used after the context has been finalized, it will keep on pushing the data through the algorithm specific transform function and thereby change the context; however the results are not meaningful and this feature is only available to mitigate timing attacks. @end deftypefun The way to read out the calculated MAC is by using the function: @deftypefun gcry_error_t gcry_mac_read (gcry_mac_hd_t @var{h}, void *@var{buffer}, size_t *@var{length}) @code{gcry_mac_read} returns the MAC after finalizing the calculation. Function copies the resulting MAC value to @var{buffer} of the length @var{length}. If @var{length} is larger than length of resulting MAC value, then length of MAC is returned through @var{length}. @end deftypefun To compare existing MAC value with recalculated MAC, one is to use the function: @deftypefun gcry_error_t gcry_mac_verify (gcry_mac_hd_t @var{h}, void *@var{buffer}, size_t @var{length}) @code{gcry_mac_verify} finalizes MAC calculation and compares result with @var{length} bytes of data in @var{buffer}. Error code @code{GPG_ERR_CHECKSUM} is returned if the MAC value in the buffer @var{buffer} does not match the MAC calculated in object @var{h}. @end deftypefun In some situations it might be hard to remember the algorithm used for the MAC calculation. The following function might be used to get that information: @deftypefun {int} gcry_mac_get_algo (gcry_mac_hd_t @var{h}) Retrieve the algorithm used with the handle @var{h}. @end deftypefun @c *********************************** @c ***** MAC info functions ********** @c *********************************** MAC algorithms are identified by internal algorithm numbers (see @code{gcry_mac_open} for a list). However, in most applications they are used by names, so two functions are available to map between string representations and MAC algorithm identifiers. @deftypefun {const char *} gcry_mac_algo_name (int @var{algo}) Map the MAC 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_mac_map_name (const char *@var{name}) Map the algorithm with @var{name} to a MAC algorithm identifier. Returns 0 if the algorithm name is not known. This function should not be used to test for the availability of an algorithm. @end deftypefun To test whether an algorithm is actually available for use, the following macro should be used: @deftypefun gcry_error_t gcry_mac_test_algo (int @var{algo}) The macro returns 0 if the MAC 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_mac_get_algo_maclen (int @var{algo}) Retrieve the length in bytes of the MAC yielded by algorithm @var{algo}. This is often used prior to @code{gcry_mac_read} to allocate sufficient memory for the MAC value. On error @code{0} is returned. @end deftypefun @deftypefun {unsigned int} gcry_mac_get_algo_keylen (@var{algo}) This function returns length of the key for MAC algorithm @var{algo}. If the algorithm supports multiple key lengths, the default supported key length is returned. On error @code{0} is returned. The key length is returned as number of octets. @end deftypefun @c ******************************************************* @c ******************* KDF ***************************** @c ******************************************************* @node Key Derivation @chapter Key Derivation @acronym{Libgcypt} provides a general purpose function to derive keys from strings. @deftypefun gpg_error_t gcry_kdf_derive ( @ @w{const void *@var{passphrase}}, @w{size_t @var{passphraselen}}, @ @w{int @var{algo}}, @w{int @var{subalgo}}, @ @w{const void *@var{salt}}, @w{size_t @var{saltlen}}, @ @w{unsigned long @var{iterations}}, @ @w{size_t @var{keysize}}, @w{void *@var{keybuffer}} ) Derive a key from a passphrase. @var{keysize} gives the requested size of the keys in octets. @var{keybuffer} is a caller provided buffer filled on success with the derived key. The input passphrase is taken from @var{passphrase} which is an arbitrary memory buffer of @var{passphraselen} octets. @var{algo} specifies the KDF algorithm to use; see below. @var{subalgo} specifies an algorithm used internally by the KDF algorithms; this is usually a hash algorithm but certain KDF algorithms may use it differently. @var{salt} is a salt of length @var{saltlen} octets, as needed by most KDF algorithms. @var{iterations} is a positive integer parameter to most KDFs. @noindent On success 0 is returned; on failure an error code. @noindent Currently supported KDFs (parameter @var{algo}): @table @code @item GCRY_KDF_SIMPLE_S2K The OpenPGP simple S2K algorithm (cf. RFC4880). Its use is strongly deprecated. @var{salt} and @var{iterations} are not needed and may be passed as @code{NULL}/@code{0}. @item GCRY_KDF_SALTED_S2K The OpenPGP salted S2K algorithm (cf. RFC4880). Usually not used. @var{iterations} is not needed and may be passed as @code{0}. @var{saltlen} must be given as 8. @item GCRY_KDF_ITERSALTED_S2K The OpenPGP iterated+salted S2K algorithm (cf. RFC4880). This is the default for most OpenPGP applications. @var{saltlen} must be given as 8. Note that OpenPGP defines a special encoding of the @var{iterations}; however this function takes the plain decoded iteration count. @item GCRY_KDF_PBKDF2 The PKCS#5 Passphrase Based Key Derivation Function number 2. @item GCRY_KDF_SCRYPT The SCRYPT Key Derivation Function. The subalgorithm is used to specify the CPU/memory cost parameter N, and the number of iterations is used for the parallelization parameter p. The block size is fixed at 8 in the current implementation. @end table @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. The MPI is stored as a signed integer. @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. The MPI is stored as an unsigned integer. @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 %u The next argument is expected to be of type @code{unsigned 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 S-expression. @item %S The next argument is expected to be of type @code{gcry_sexp_t} and a copy of that S-expression is embedded in the resulting S-expression. The argument needs to be a regular S-expression, starting with a parenthesis. @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}. If the S-expression is stored in secure memory it explicitly zeroises that memory; note that this is done in addition to the zeroisation always done when freeing secure memory. @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 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 is called the "type" and should always exist per S-expression specification and in general 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 {void *} gcry_sexp_nth_buffer (@w{const gcry_sexp_t @var{list}}, @w{int @var{number}}, @w{size_t *@var{rlength}}) This function is used to get data from a @var{list}. A malloced buffer with the actual data at list index @var{number} is returned and the length of this buffer will be stored to @var{rlength}. If there is no data at the given index or the index represents another list, @code{NULL} is returned. The caller must release the result using @code{gcry_free}. @noindent Here is an example on how to extract and print the CRC value from the S-expression @samp{(hash crc32 #23ed00d7)}: @example size_t len; char *value; value = gcry_sexp_nth_buffer (list, 2, &len); if (value) fwrite (value, len, 1, stdout); gcry_free (value); @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. If you use this function to parse results of a public key function, you most likely want to use @code{GCRYMPI_FMT_USG}. @end deftypefun @deftypefun gpg_error_t gcry_sexp_extract_param ( @ @w{gcry_sexp_t @var{sexp}}, @ @w{const char *@var{path}}, @ @w{const char *@var{list}}, ...) Extract parameters from an S-expression using a list of parameter names. The names of these parameters are specified in LIST. White space between the parameter names are ignored. Some special characters may be given to control the conversion: @table @samp @item + Switch to unsigned integer format (GCRYMPI_FMT_USG). This is the default mode. @item - Switch to standard signed format (GCRYMPI_FMT_STD). @item / Switch to opaque MPI format. The resulting MPIs may not be used for computations; see @code{gcry_mpi_get_opaque} for details. @item & Switch to buffer descriptor mode. See below for details. @item ? If immediately following a parameter letter (no white space allowed), that parameter is considered optional. @end table In general parameter names are single letters. To use a string for a parameter name, enclose the name in single quotes. Unless in buffer descriptor mode for each parameter name a pointer to an @code{gcry_mpi_t} variable is expected that must be set to @code{NULL} prior to invoking this function, and finally a @code{NULL} is expected. For example @example _gcry_sexp_extract_param (key, NULL, "n/x+e d-'foo'", &mpi_n, &mpi_x, &mpi_e, &mpi_foo, NULL) @end example stores the parameter 'n' from @var{key} as an unsigned MPI into @var{mpi_n}, the parameter 'x' as an opaque MPI into @var{mpi_x}, the parameter 'e' again as an unsigned MPI into @var{mpi_e}, and the parameter 'foo' as a signed MPI. @var{path} is an optional string used to locate a token. The exclamation mark separated tokens are used via @code{gcry_sexp_find_token} to find a start point inside the S-expression. In buffer descriptor mode a pointer to a @code{gcry_buffer_t} descriptor is expected instead of a pointer to an MPI. The caller may use two different operation modes here: If the @var{data} field of the provided descriptor is @code{NULL}, the function allocates a new buffer and stores it at @var{data}; the other fields are set accordingly with @var{off} set to 0. If @var{data} is not @code{NULL}, the function assumes that the @var{data}, @var{size}, and @var{off} fields specify a buffer where to but the value of the respective parameter; on return the @var{len} field receives the number of bytes copied to that buffer; in case the buffer is too small, the function immediately returns with an error code (and @var{len} is set to 0). The function returns 0 on success. On error an error code is returned, all passed MPIs that might have been allocated up to this point are deallocated and set to @code{NULL}, and all passed buffers are either truncated if the caller supplied the buffer, or deallocated if the function allocated the buffer. @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. * EC functions:: Elliptic curve related functions. * 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 @deftp {Data type} {gcry_mpi_point_t} This type represents an object to hold a point for elliptic curve math. @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} but with the constant and immutable flags cleared. @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 @deftypefun void gcry_mpi_snatch (@w{gcry_mpi_t @var{w}}, @ @w{const gcry_mpi_t @var{u}}) Set @var{u} into @var{w} and release @var{u}. If @var{w} is @code{NULL} only @var{u} will be released. @end deftypefun @deftypefun void gcry_mpi_neg (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}) Set the sign of @var{w} to the negative of @var{u}. @end deftypefun @deftypefun void gcry_mpi_abs (@w{gcry_mpi_t @var{w}}) Clear the sign of @var{w}. @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}. A @var{buflen} larger than 16 MiByte will be rejected. 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. Note that @code{gcry_mpi_print} stores a @code{0} as a string of zero length. @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. A length header indicating a length of more than 16384 is not allowed. @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 string with each byte of the MPI encoded as 2 hex digits. Negative numbers are prefix with a minus sign and in addition the high bit is always zero to make clear that an explicit sign ist used. 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}. Even if @var{nbytes} is zero, the function allocates at least one byte and store a zero there. Thus with formats @code{GCRYMPI_FMT_STD} and @code{GCRYMPI_FMT_USG} the caller may safely set a returned length of 0 to 1 to represent a zero as a 1 byte string. @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}. If both numbers are opaque values (cf, gcry_mpi_set_opaque) the comparison is done by checking the bit sizes using memcmp. If only one number is an opaque value, the opaque value is less than the other number. @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 @deftypefun int gcry_mpi_is_neg (@w{const gcry_mpi_t @var{a}}) Return 1 if @var{a} is less than zero; return 0 if zero or positive. @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 EC functions @section EC functions @noindent Libgcrypt provides an API to access low level functions used by its elliptic curve implementation. These functions allow to implement elliptic curve methods for which no explicit support is available. @deftypefun gcry_mpi_point_t gcry_mpi_point_new (@w{unsigned int @var{nbits}}) Allocate a new point object, initialize it to 0, and allocate enough memory for a points of at least @var{nbits}. This pre-allocation yields only a small performance win and is not really necessary because Libgcrypt automatically re-allocates the required memory. Using 0 for @var{nbits} is usually the right thing to do. @end deftypefun @deftypefun void gcry_mpi_point_release (@w{gcry_mpi_point_t @var{point}}) Release @var{point} and free all associated resources. Passing @code{NULL} is allowed and ignored. @end deftypefun @deftypefun void gcry_mpi_point_get (@w{gcry_mpi_t @var{x}}, @ @w{gcry_mpi_t @var{y}}, @w{gcry_mpi_t @var{z}}, @ @w{gcry_mpi_point_t @var{point}}) Store the projective coordinates from @var{point} into the MPIs @var{x}, @var{y}, and @var{z}. If a coordinate is not required, @code{NULL} may be used for @var{x}, @var{y}, or @var{z}. @end deftypefun @deftypefun void gcry_mpi_point_snatch_get (@w{gcry_mpi_t @var{x}}, @ @w{gcry_mpi_t @var{y}}, @w{gcry_mpi_t @var{z}}, @ @w{gcry_mpi_point_t @var{point}}) Store the projective coordinates from @var{point} into the MPIs @var{x}, @var{y}, and @var{z}. If a coordinate is not required, @code{NULL} may be used for @var{x}, @var{y}, or @var{z}. The object @var{point} is then released. Using this function instead of @code{gcry_mpi_point_get} and @code{gcry_mpi_point_release} has the advantage of avoiding some extra memory allocations and copies. @end deftypefun @deftypefun gcry_mpi_point_t gcry_mpi_point_set ( @ @w{gcry_mpi_point_t @var{point}}, @ @w{gcry_mpi_t @var{x}}, @w{gcry_mpi_t @var{y}}, @w{gcry_mpi_t @var{z}}) Store the projective coordinates from @var{x}, @var{y}, and @var{z} into @var{point}. If a coordinate is given as @code{NULL}, the value 0 is used. If @code{NULL} is used for @var{point} a new point object is allocated and returned. Returns @var{point} or the newly allocated point object. @end deftypefun @deftypefun gcry_mpi_point_t gcry_mpi_point_snatch_set ( @ @w{gcry_mpi_point_t @var{point}}, @ @w{gcry_mpi_t @var{x}}, @w{gcry_mpi_t @var{y}}, @w{gcry_mpi_t @var{z}}) Store the projective coordinates from @var{x}, @var{y}, and @var{z} into @var{point}. If a coordinate is given as @code{NULL}, the value 0 is used. If @code{NULL} is used for @var{point} a new point object is allocated and returned. The MPIs @var{x}, @var{y}, and @var{z} are released. Using this function instead of @code{gcry_mpi_point_set} and 3 calls to @code{gcry_mpi_release} has the advantage of avoiding some extra memory allocations and copies. Returns @var{point} or the newly allocated point object. @end deftypefun @anchor{gcry_mpi_ec_new} @deftypefun gpg_error_t gcry_mpi_ec_new (@w{gcry_ctx_t *@var{r_ctx}}, @ @w{gcry_sexp_t @var{keyparam}}, @w{const char *@var{curvename}}) Allocate a new context for elliptic curve operations. If @var{keyparam} is given it specifies the parameters of the curve (@pxref{ecc_keyparam}). If @var{curvename} is given in addition to @var{keyparam} and the key parameters do not include a named curve reference, the string @var{curvename} is used to fill in missing parameters. If only @var{curvename} is given, the context is initialized for this named curve. If a parameter specifying a point (e.g. @code{g} or @code{q}) is not found, the parser looks for a non-encoded point by appending @code{.x}, @code{.y}, and @code{.z} to the parameter name and looking them all up to create a point. A parameter with the suffix @code{.z} is optional and defaults to 1. On success the function returns 0 and stores the new context object at @var{r_ctx}; this object eventually needs to be released (@pxref{gcry_ctx_release}). On error the function stores @code{NULL} at @var{r_ctx} and returns an error code. @end deftypefun @deftypefun gcry_mpi_t gcry_mpi_ec_get_mpi ( @ @w{const char *@var{name}}, @w{gcry_ctx_t @var{ctx}}, @w{int @var{copy}}) Return the MPI with @var{name} from the context @var{ctx}. If not found @code{NULL} is returned. If the returned MPI may later be modified, it is suggested to pass @code{1} to @var{copy}, so that the function guarantees that a modifiable copy of the MPI is returned. If @code{0} is used for @var{copy}, this function may return a constant flagged MPI. In any case @code{gcry_mpi_release} needs to be called to release the result. For valid names @ref{ecc_keyparam}. If the public key @code{q} is requested but only the private key @code{d} is available, @code{q} will be recomputed on the fly. If a point parameter is requested it is returned as an uncompressed encoded point unless these special names are used: @table @var @item q@@eddsa Return an EdDSA style compressed point. This is only supported for Twisted Edwards curves. @end table @end deftypefun @deftypefun gcry_mpi_point_t gcry_mpi_ec_get_point ( @ @w{const char *@var{name}}, @w{gcry_ctx_t @var{ctx}}, @w{int @var{copy}}) Return the point with @var{name} from the context @var{ctx}. If not found @code{NULL} is returned. If the returned MPI may later be modified, it is suggested to pass @code{1} to @var{copy}, so that the function guarantees that a modifiable copy of the MPI is returned. If @code{0} is used for @var{copy}, this function may return a constant flagged point. In any case @code{gcry_mpi_point_release} needs to be called to release the result. If the public key @code{q} is requested but only the private key @code{d} is available, @code{q} will be recomputed on the fly. @end deftypefun @deftypefun gpg_error_t gcry_mpi_ec_set_mpi ( @ @w{const char *@var{name}}, @w{gcry_mpi_t @var{newvalue}}, @ @w{gcry_ctx_t @var{ctx}}) Store the MPI @var{newvalue} at @var{name} into the context @var{ctx}. On success @code{0} is returned; on error an error code. Valid names are the MPI parameters of an elliptic curve (@pxref{ecc_keyparam}). @end deftypefun @deftypefun gpg_error_t gcry_mpi_ec_set_point ( @ @w{const char *@var{name}}, @w{gcry_mpi_point_t @var{newvalue}}, @ @w{gcry_ctx_t @var{ctx}}) Store the point @var{newvalue} at @var{name} into the context @var{ctx}. On success @code{0} is returned; on error an error code. Valid names are the point parameters of an elliptic curve (@pxref{ecc_keyparam}). @end deftypefun @deftypefun gpg_err_code_t gcry_mpi_ec_decode_point ( @ @w{mpi_point_t @var{result}}, @w{gcry_mpi_t @var{value}}, @ @w{gcry_ctx_t @var{ctx}}) Decode the point given as an MPI in @var{value} and store at @var{result}. To decide which encoding is used the function takes a context @var{ctx} which can be created with @code{gcry_mpi_ec_new}. If @code{NULL} is given for the context the function assumes a 0x04 prefixed uncompressed encoding. On error an error code is returned and @var{result} might be changed. @end deftypefun @deftypefun int gcry_mpi_ec_get_affine ( @ @w{gcry_mpi_t @var{x}}, @w{gcry_mpi_t @var{y}}, @ @w{gcry_mpi_point_t @var{point}}, @w{gcry_ctx_t @var{ctx}}) Compute the affine coordinates from the projective coordinates in @var{point} and store them into @var{x} and @var{y}. If one coordinate is not required, @code{NULL} may be passed to @var{x} or @var{y}. @var{ctx} is the context object which has been created using @code{gcry_mpi_ec_new}. Returns 0 on success or not 0 if @var{point} is at infinity. Note that you can use @code{gcry_mpi_ec_set_point} with the value @code{GCRYMPI_CONST_ONE} for @var{z} to convert affine coordinates back into projective coordinates. @end deftypefun @deftypefun void gcry_mpi_ec_dup ( @ @w{gcry_mpi_point_t @var{w}}, @w{gcry_mpi_point_t @var{u}}, @ @w{gcry_ctx_t @var{ctx}}) Double the point @var{u} of the elliptic curve described by @var{ctx} and store the result into @var{w}. @end deftypefun @deftypefun void gcry_mpi_ec_add ( @ @w{gcry_mpi_point_t @var{w}}, @w{gcry_mpi_point_t @var{u}}, @ @w{gcry_mpi_point_t @var{v}}, @w{gcry_ctx_t @var{ctx}}) Add the points @var{u} and @var{v} of the elliptic curve described by @var{ctx} and store the result into @var{w}. @end deftypefun @deftypefun void gcry_mpi_ec_sub ( @ @w{gcry_mpi_point_t @var{w}}, @w{gcry_mpi_point_t @var{u}}, @ @w{gcry_mpi_point_t @var{v}}, @w{gcry_ctx_t @var{ctx}}) Subtracts the point @var{v} from the point @var{u} of the elliptic curve described by @var{ctx} and store the result into @var{w}. Only Twisted Edwards curves are supported for now. @end deftypefun @deftypefun void gcry_mpi_ec_mul ( @ @w{gcry_mpi_point_t @var{w}}, @w{gcry_mpi_t @var{n}}, @ @w{gcry_mpi_point_t @var{u}}, @w{gcry_ctx_t @var{ctx}}) Multiply the point @var{u} of the elliptic curve described by @var{ctx} by @var{n} and store the result into @var{w}. @end deftypefun @deftypefun int gcry_mpi_ec_curve_point ( @ @w{gcry_mpi_point_t @var{point}}, @w{gcry_ctx_t @var{ctx}}) Return true if @var{point} is on the elliptic curve described by @var{ctx}. @end deftypefun @node Miscellaneous @section Miscellaneous An MPI data type is allowed to be ``misused'' to store an arbitrary value. Two functions implement this kludge: @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}). Ownership of @var{p} is taken by this function and thus the user may not use dereference the passed value anymore. It is required that them memory referenced by @var{p} has been allocated in a way that @code{gcry_free} is able to release it. 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 gcry_mpi_t gcry_mpi_set_opaque_copy (@w{gcry_mpi_t @var{a}}, @w{const void *@var{p}}, @w{unsigned int @var{nbits}}) Same as @code{gcry_mpi_set_opaque} but ownership of @var{p} is not taken instead a copy of @var{p} is used. @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 Each MPI has an associated set of flags for special purposes. The currently defined flags are: @table @code @item GCRYMPI_FLAG_SECURE Setting this flag converts @var{a} into an MPI stored in "secure memory". Clearing this flag is not allowed. @item GCRYMPI_FLAG_OPAQUE This is an interanl flag, indicating the an opaque valuue and not an integer is stored. This is an read-only flag; it may not be set or cleared. @item GCRYMPI_FLAG_IMMUTABLE If this flag is set, the MPI is marked as immutable. Setting or changing the value of that MPI is ignored and an error message is logged. The flag is sometimes useful for debugging. @item GCRYMPI_FLAG_CONST If this flag is set, the MPI is marked as a constant and as immutable Setting or changing the value of that MPI is ignored and an error message is logged. Such an MPI will never be deallocated and may thus be used without copying. Note that using gcry_mpi_copy will return a copy of that constant with this and the immutable flag cleared. A few commonly used constants are pre-defined and accessible using the macros @code{GCRYMPI_CONST_ONE}, @code{GCRYMPI_CONST_TWO}, @code{GCRYMPI_CONST_THREE}, @code{GCRYMPI_CONST_FOUR}, and @code{GCRYMPI_CONST_EIGHT}. @item GCRYMPI_FLAG_USER1 @itemx GCRYMPI_FLAG_USER2 @itemx GCRYMPI_FLAG_USER3 @itemx GCRYMPI_FLAG_USER4 These flags are reserved for use by the application. @end table @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}. The only allowed flags are @code{GCRYMPI_FLAG_SECURE}, @code{GCRYMPI_FLAG_IMMUTABLE}, and @code{GCRYMPI_FLAG_CONST}. @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}. The only allowed flag is @code{GCRYMPI_FLAG_IMMUTABLE} but only if @code{GCRYMPI_FLAG_CONST} is not set. If @code{GCRYMPI_FLAG_CONST} is set, clearing @code{GCRYMPI_FLAG_IMMUTABLE} will simply be ignored. @end deftypefun o @deftypefun int gcry_mpi_get_flag (@w{gcry_mpi_t @var{a}}, @ @w{enum gcry_mpi_flag @var{flag}}) Return true if @var{flag} is set for @var{a}. @end deftypefun To put a random value into an MPI, the following convenience function may be used: @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 non-negative number 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 whether 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. * Context management:: Functions related with context management. * Buffer description:: A data type to describe buffers. @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}, size_t @var{m}) This function allocates a cleared block of memory (i.e. initialized with zero bytes) long enough to contain a vector of @var{n} elements, each of size @var{m} bytes. On success it returns a pointer to the memory block; in an out-of-core condition, it returns NULL. @end deftypefun @deftypefun {void *} gcry_calloc_secure (size_t @var{n}, size_t @var{m}) 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 @node Context management @section Context management Some function make use of a context object. As of now there are only a few math functions. However, future versions of Libgcrypt may make more use of this context object. @deftp {Data type} {gcry_ctx_t} This type is used to refer to the general purpose context object. @end deftp @anchor{gcry_ctx_release} @deftypefun void gcry_ctx_release (gcry_ctx_t @var{ctx}) Release the context object @var{ctx} and all associated resources. A @code{NULL} passed as @var{ctx} is ignored. @end deftypefun @node Buffer description @section Buffer description To help hashing non-contiguous areas of memory a general purpose data type is defined: @deftp {Data type} {gcry_buffer_t} This type is a structure to describe a buffer. The user should make sure that this structure is initialized to zero. The available fields of this structure are: @table @code @item .size This is either 0 for no information available or indicates the allocated length of the buffer. @item .off This is the offset into the buffer. @item .len This is the valid length of the buffer starting at @code{.off}. @item .data This is the address of the buffer. @end table @end deftp @c ********************************************************** @c ********************* Tools **************************** @c ********************************************************** @node Tools @chapter Tools @menu * hmac256:: A standalone HMAC-SHA-256 implementation @end menu @manpage hmac256.1 @node hmac256 @section A HMAC-SHA-256 tool @ifset manverb .B hmac256 \- Compute an HMAC-SHA-256 MAC @end ifset @mansect synopsis @ifset manverb .B hmac256 .RB [ \-\-binary ] .I key .I [FILENAME] @end ifset @mansect description This is a standalone HMAC-SHA-256 implementation used to compute an HMAC-SHA-256 message authentication code. The tool has originally been developed as a second implementation for Libgcrypt to allow comparing against the primary implementation and to be used for internal consistency checks. It should not be used for sensitive data because no mechanisms to clear the stack etc are used. The code has been written in a highly portable manner and requires only a few standard definitions to be provided in a config.h file. @noindent @command{hmac256} is commonly invoked as @example hmac256 "This is my key" foo.txt @end example @noindent This compute the MAC on the file @file{foo.txt} using the key given on the command line. @mansect options @noindent @command{hmac256} understands these options: @table @gnupgtabopt @item --binary Print the MAC as a binary string. The default is to print the MAC encoded has lower case hex digits. @item --version Print version of the program and exit. @end table @mansect see also @ifset isman @command{sha256sum}(1) @end ifset @manpause @c ********************************************************** @c **************** Environment Variables ***************** @c ********************************************************** @node Configuration -@chapter Configuration files and evironment variables +@chapter Configuration files and environment variables This chapter describes which files and environment variables can be used to change the behaviour of Libgcrypt. @noindent The environment variables considered by Libgcrypt are: @table @code @item GCRYPT_BARRETT @cindex GCRYPT_BARRETT By setting this variable to any value a different algorithm for modular reduction is used for ECC. @item GCRYPT_RNDUNIX_DBG @item GCRYPT_RNDUNIX_DBGALL @cindex GCRYPT_RNDUNIX_DBG @cindex GCRYPT_RNDUNIX_DBGALL These two environment variables are used to enable debug output for the rndunix entropy gatherer, which is used on systems lacking a /dev/random device. The value of @code{GCRYPT_RNDUNIX_DBG} is a file name or @code{-} for stdout. Debug output is the written to this file. By setting @code{GCRYPT_RNDUNIX_DBGALL} to any value the debug output will be more verbose. @item GCRYPT_RNDW32_NOPERF @cindex GCRYPT_RNDW32_NOPERF Setting this environment variable on Windows to any value disables the use of performance data (@code{HKEY_PERFORMANCE_DATA}) as source for entropy. On some older Windows systems this could help to speed up the creation of random numbers but also decreases the amount of data used to init the random number generator. @item GCRYPT_RNDW32_DBG @cindex GCRYPT_RNDW32_DBG Setting the value of this variable to a positive integer logs information about the Windows entropy gatherer using the standard log interface. @item HOME @cindex HOME This is used to locate the socket to connect to the EGD random daemon. The EGD can be used on system without a /dev/random to speed up the random number generator. It is not needed on the majority of today's operating systems and support for EGD requires the use of a configure option at build time. @end table @noindent The files which Libgcrypt uses to retrieve system information and the files which can be created by the user to modify Libgcrypt's behavior are: @table @file @item /etc/gcrypt/hwf.deny @cindex /etc/gcrypt/hwf.deny This file can be used to disable the use of hardware based optimizations, @pxref{hardware features}. @item /etc/gcrypt/fips_enabled @itemx /proc/sys/crypto/fips_enabled @cindex /etc/gcrypt/fips_enabled @cindex fips_enabled On Linux these files are used to enable FIPS mode, @pxref{enabling fips mode}. @item /proc/cpuinfo @itemx /proc/self/auxv @cindex /proc/cpuinfo @cindex /proc/self/auxv On Linux running on the ARM architecture, these files are used to read hardware capabilities of the CPU. @end table @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 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 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. 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_WEAK_RANDOM} random level. @cindex X9.31 @cindex FIPS 186 The algorithm used for RSA and DSA key generation depends on whether Libgcrypt is operated in standard or in FIPS mode. In standard mode an algorithm based on the Lim-Lee prime number generator is used. In FIPS mode RSA keys are generated as specified in ANSI X9.31 (1998) and DSA keys as specified in FIPS 186-2. @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 schemes 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 To support the generation of RSA and DSA keys in FIPS mode according to X9.31 and FIPS 186-2, Libgcrypt implements two additional prime generation functions: @code{_gcry_derive_x931_prime} and @code{_gcry_generate_fips186_2_prime}. These functions are internal and not available through the public API. @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 supported hardware RNG is the Padlock engine of VIA (Centaur) CPUs and x86 CPUs with the RDRAND instruction. 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 SHA-1 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. +@c FIXME: The design and implementation 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/random} 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 stuck 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 feature 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 original random value. The encrypted result is then decrypted and checked that it matches 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 condition 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 No code is loaded at runtime. @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 library 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 key generation refuses to create a key with a keysize of less than 1024 bits. @item DSA key generation refuses to create a key with a keysize other than 1024 bits. @item The @code{transient-key} flag for RSA and DSA 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 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 The digest algorithm MD5 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 function @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 introduced 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 running 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 initialization function @code{gcry_check_version}. @item 3 Init to Self-Test is either triggered by a dedicated API call or implicit by invoking a libgrypt service controlled by the FSM. @item 4 Self-Test to Operational is triggered after all self-tests passed successfully. @item 5 Operational to Shutdown is an artificial 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 triggered 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 artificial state to document that Libgcrypt has not ye been initialized but the process is about to terminate. @item 12 Power-On to Fatal-Error will be triggered if certain Libgcrypt functions are used without having reached the Init state. @item 13 Self-Test to Fatal-Error is triggered by severe errors in Libgcrypt while running self-tests. @item 14 Self-Test to Error is triggered 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 triggered 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 ******************************************** @section FIPS Miscellaneous Information Libgcrypt does not do any key management on itself; the application needs to care about it. Keys which are passed to Libgcrypt should be allocated in secure memory as available with the functions @code{gcry_malloc_secure} and @code{gcry_calloc_secure}. By calling @code{gcry_free} on this memory, the memory and thus the keys are overwritten with zero bytes before releasing the memory. For use with the random number generator, Libgcrypt generates 3 internal keys which are stored in the encryption contexts used by the RNG. These keys are stored in secure memory for the lifetime of the process. Application are required to use @code{GCRYCTL_TERM_SECMEM} before process termination. This will zero out the entire secure memory and thus also the encryption contexts with these keys. @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 daemon 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/mpi/alpha/README b/mpi/alpha/README index 55c0a291..00addfd3 100644 --- a/mpi/alpha/README +++ b/mpi/alpha/README @@ -1,53 +1,53 @@ This directory contains mpn functions optimized for DEC Alpha processors. RELEVANT OPTIMIZATION ISSUES EV4 1. This chip has very limited store bandwidth. The on-chip L1 cache is -write-through, and a cache line is transfered from the store buffer to the +write-through, and a cache line is transferred from the store buffer to the off-chip L2 in as much 15 cycles on most systems. This delay hurts mpn_add_n, mpn_sub_n, mpn_lshift, and mpn_rshift. 2. Pairing is possible between memory instructions and integer arithmetic instructions. 3. mulq and umulh is documented to have a latency of 23 cycles, but 2 of these cycles are pipelined. Thus, multiply instructions can be issued at a rate of one each 21nd cycle. EV5 1. The memory bandwidth of this chip seems excellent, both for loads and stores. Even when the working set is larger than the on-chip L1 and L2 -caches, the perfromance remain almost unaffected. +caches, the performance remain almost unaffected. 2. mulq has a measured latency of 13 cycles and an issue rate of 1 each 8th cycle. umulh has a measured latency of 15 cycles and an issue rate of 1 each 10th cycle. But the exact timing is somewhat confusing. 3. mpn_add_n. With 4-fold unrolling, we need 37 instructions, whereof 12 are memory operations. This will take at least ceil(37/2) [dual issue] + 1 [taken branch] = 20 cycles We have 12 memory cycles, plus 4 after-store conflict cycles, or 16 data cache cycles, which should be completely hidden in the 20 issue cycles. The computation is inherently serial, with these dependencies: addq / \ addq cmpult | | cmpult | \ / or I.e., there is a 4 cycle path for each limb, making 16 cycles the absolute minimum. We could replace the `or' with a cmoveq/cmovne, which would save a cycle on EV5, but that might waste a cycle on EV4. Also, cmov takes 2 cycles. addq / \ addq cmpult | \ cmpult -> cmovne STATUS diff --git a/mpi/ec.c b/mpi/ec.c index 26dd9478..016af005 100644 --- a/mpi/ec.c +++ b/mpi/ec.c @@ -1,1555 +1,1555 @@ /* ec.c - Elliptic Curve functions * Copyright (C) 2007 Free Software Foundation, Inc. * Copyright (C) 2013 g10 Code GmbH * * 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 . */ #include #include #include #include #include "mpi-internal.h" #include "longlong.h" #include "g10lib.h" #include "context.h" #include "ec-context.h" #include "ec-internal.h" #define point_init(a) _gcry_mpi_point_init ((a)) #define point_free(a) _gcry_mpi_point_free_parts ((a)) -/* Print a point using the log fucntions. If CTX is not NULL affine +/* Print a point using the log functions. If CTX is not NULL affine coordinates will be printed. */ void _gcry_mpi_point_log (const char *name, mpi_point_t point, mpi_ec_t ctx) { gcry_mpi_t x, y; char buf[100]; if (!point) { snprintf (buf, sizeof buf - 1, "%s.*", name); log_mpidump (buf, NULL); return; } snprintf (buf, sizeof buf - 1, "%s.X", name); if (ctx) { x = mpi_new (0); y = mpi_new (0); } if (!ctx || _gcry_mpi_ec_get_affine (x, y, point, ctx)) { log_mpidump (buf, point->x); buf[strlen(buf)-1] = 'Y'; log_mpidump (buf, point->y); buf[strlen(buf)-1] = 'Z'; log_mpidump (buf, point->z); } else { buf[strlen(buf)-1] = 'x'; log_mpidump (buf, x); buf[strlen(buf)-1] = 'y'; log_mpidump (buf, y); } if (ctx) { _gcry_mpi_release (x); _gcry_mpi_release (y); } } /* Create a new point option. NBITS gives the size in bits of one coordinate; it is only used to pre-allocate some resources and might also be passed as 0 to use a default value. */ mpi_point_t _gcry_mpi_point_new (unsigned int nbits) { mpi_point_t p; (void)nbits; /* Currently not used. */ p = xmalloc (sizeof *p); _gcry_mpi_point_init (p); return p; } /* Release the point object P. P may be NULL. */ void _gcry_mpi_point_release (mpi_point_t p) { if (p) { _gcry_mpi_point_free_parts (p); xfree (p); } } /* Initialize the fields of a point object. gcry_mpi_point_free_parts may be used to release the fields. */ void _gcry_mpi_point_init (mpi_point_t p) { p->x = mpi_new (0); p->y = mpi_new (0); p->z = mpi_new (0); } /* Release the parts of a point object. */ void _gcry_mpi_point_free_parts (mpi_point_t p) { mpi_free (p->x); p->x = NULL; mpi_free (p->y); p->y = NULL; mpi_free (p->z); p->z = NULL; } /* Set the value from S into D. */ static void point_set (mpi_point_t d, mpi_point_t s) { mpi_set (d->x, s->x); mpi_set (d->y, s->y); mpi_set (d->z, s->z); } static void point_resize (mpi_point_t p, mpi_ec_t ctx) { /* * For now, we allocate enough limbs for our EC computation of ec_*. * Once we will improve ec_* to be constant size (and constant * time), NLIMBS can be ctx->p->nlimbs. */ size_t nlimbs = 2*ctx->p->nlimbs+1; mpi_resize (p->x, nlimbs); if (ctx->model != MPI_EC_MONTGOMERY) mpi_resize (p->y, nlimbs); mpi_resize (p->z, nlimbs); } static void point_swap_cond (mpi_point_t d, mpi_point_t s, unsigned long swap, mpi_ec_t ctx) { mpi_swap_cond (d->x, s->x, swap); if (ctx->model != MPI_EC_MONTGOMERY) mpi_swap_cond (d->y, s->y, swap); mpi_swap_cond (d->z, s->z, swap); } /* Set the projective coordinates from POINT into X, Y, and Z. If a coordinate is not required, X, Y, or Z may be passed as NULL. */ void _gcry_mpi_point_get (gcry_mpi_t x, gcry_mpi_t y, gcry_mpi_t z, mpi_point_t point) { if (x) mpi_set (x, point->x); if (y) mpi_set (y, point->y); if (z) mpi_set (z, point->z); } /* Set the projective coordinates from POINT into X, Y, and Z and release POINT. If a coordinate is not required, X, Y, or Z may be passed as NULL. */ void _gcry_mpi_point_snatch_get (gcry_mpi_t x, gcry_mpi_t y, gcry_mpi_t z, mpi_point_t point) { mpi_snatch (x, point->x); mpi_snatch (y, point->y); mpi_snatch (z, point->z); xfree (point); } /* Set the projective coordinates from X, Y, and Z into POINT. If a coordinate is given as NULL, the value 0 is stored into point. If POINT is given as NULL a new point object is allocated. Returns POINT or the newly allocated point object. */ mpi_point_t _gcry_mpi_point_set (mpi_point_t point, gcry_mpi_t x, gcry_mpi_t y, gcry_mpi_t z) { if (!point) point = mpi_point_new (0); if (x) mpi_set (point->x, x); else mpi_clear (point->x); if (y) mpi_set (point->y, y); else mpi_clear (point->y); if (z) mpi_set (point->z, z); else mpi_clear (point->z); return point; } /* Set the projective coordinates from X, Y, and Z into POINT. If a coordinate is given as NULL, the value 0 is stored into point. If POINT is given as NULL a new point object is allocated. The coordinates X, Y, and Z are released. Returns POINT or the newly allocated point object. */ mpi_point_t _gcry_mpi_point_snatch_set (mpi_point_t point, gcry_mpi_t x, gcry_mpi_t y, gcry_mpi_t z) { if (!point) point = mpi_point_new (0); if (x) mpi_snatch (point->x, x); else mpi_clear (point->x); if (y) mpi_snatch (point->y, y); else mpi_clear (point->y); if (z) mpi_snatch (point->z, z); else mpi_clear (point->z); return point; } /* W = W mod P. */ static void ec_mod (gcry_mpi_t w, mpi_ec_t ec) { if (0 && ec->dialect == ECC_DIALECT_ED25519) _gcry_mpi_ec_ed25519_mod (w); else if (ec->t.p_barrett) _gcry_mpi_mod_barrett (w, w, ec->t.p_barrett); else _gcry_mpi_mod (w, w, ec->p); } static void ec_addm (gcry_mpi_t w, gcry_mpi_t u, gcry_mpi_t v, mpi_ec_t ctx) { mpi_add (w, u, v); ec_mod (w, ctx); } static void ec_subm (gcry_mpi_t w, gcry_mpi_t u, gcry_mpi_t v, mpi_ec_t ec) { mpi_sub (w, u, v); while (w->sign) mpi_add (w, w, ec->p); /*ec_mod (w, ec);*/ } static void ec_mulm (gcry_mpi_t w, gcry_mpi_t u, gcry_mpi_t v, mpi_ec_t ctx) { mpi_mul (w, u, v); ec_mod (w, ctx); } /* W = 2 * U mod P. */ static void ec_mul2 (gcry_mpi_t w, gcry_mpi_t u, mpi_ec_t ctx) { mpi_lshift (w, u, 1); ec_mod (w, ctx); } static void ec_powm (gcry_mpi_t w, const gcry_mpi_t b, const gcry_mpi_t e, mpi_ec_t ctx) { mpi_powm (w, b, e, ctx->p); /* _gcry_mpi_abs (w); */ } /* Shortcut for ec_powm (B, B, mpi_const (MPI_C_TWO), ctx); for easier optimization. */ static void ec_pow2 (gcry_mpi_t w, const gcry_mpi_t b, mpi_ec_t ctx) { /* Using mpi_mul is slightly faster (at least on amd64). */ /* mpi_powm (w, b, mpi_const (MPI_C_TWO), ctx->p); */ ec_mulm (w, b, b, ctx); } /* Shortcut for ec_powm (B, B, mpi_const (MPI_C_THREE), ctx); for easier optimization. */ static void ec_pow3 (gcry_mpi_t w, const gcry_mpi_t b, mpi_ec_t ctx) { mpi_powm (w, b, mpi_const (MPI_C_THREE), ctx->p); } static void ec_invm (gcry_mpi_t x, gcry_mpi_t a, mpi_ec_t ctx) { if (!mpi_invm (x, a, ctx->p)) { log_error ("ec_invm: inverse does not exist:\n"); log_mpidump (" a", a); log_mpidump (" p", ctx->p); } } /* Force recomputation of all helper variables. */ void _gcry_mpi_ec_get_reset (mpi_ec_t ec) { ec->t.valid.a_is_pminus3 = 0; ec->t.valid.two_inv_p = 0; } /* Accessor for helper variable. */ static int ec_get_a_is_pminus3 (mpi_ec_t ec) { gcry_mpi_t tmp; if (!ec->t.valid.a_is_pminus3) { ec->t.valid.a_is_pminus3 = 1; tmp = mpi_alloc_like (ec->p); mpi_sub_ui (tmp, ec->p, 3); ec->t.a_is_pminus3 = !mpi_cmp (ec->a, tmp); mpi_free (tmp); } return ec->t.a_is_pminus3; } /* Accessor for helper variable. */ static gcry_mpi_t ec_get_two_inv_p (mpi_ec_t ec) { if (!ec->t.valid.two_inv_p) { ec->t.valid.two_inv_p = 1; if (!ec->t.two_inv_p) ec->t.two_inv_p = mpi_alloc (0); ec_invm (ec->t.two_inv_p, mpi_const (MPI_C_TWO), ec); } return ec->t.two_inv_p; } /* This function initialized a context for elliptic curve based on the field GF(p). P is the prime specifying this field, A is the first coefficient. CTX is expected to be zeroized. */ static void ec_p_init (mpi_ec_t ctx, enum gcry_mpi_ec_models model, enum ecc_dialects dialect, int flags, gcry_mpi_t p, gcry_mpi_t a, gcry_mpi_t b) { int i; static int use_barrett; if (!use_barrett) { if (getenv ("GCRYPT_BARRETT")) use_barrett = 1; else use_barrett = -1; } /* Fixme: Do we want to check some constraints? e.g. a < p */ ctx->model = model; ctx->dialect = dialect; ctx->flags = flags; if (dialect == ECC_DIALECT_ED25519) ctx->nbits = 256; else ctx->nbits = mpi_get_nbits (p); ctx->p = mpi_copy (p); ctx->a = mpi_copy (a); ctx->b = mpi_copy (b); ctx->t.p_barrett = use_barrett > 0? _gcry_mpi_barrett_init (ctx->p, 0):NULL; _gcry_mpi_ec_get_reset (ctx); /* Allocate scratch variables. */ for (i=0; i< DIM(ctx->t.scratch); i++) ctx->t.scratch[i] = mpi_alloc_like (ctx->p); /* Prepare for fast reduction. */ /* FIXME: need a test for NIST values. However it does not gain us any real advantage, for 384 bits it is actually slower than using mpi_mulm. */ /* ctx->nist_nbits = mpi_get_nbits (ctx->p); */ /* if (ctx->nist_nbits == 192) */ /* { */ /* for (i=0; i < 4; i++) */ /* ctx->s[i] = mpi_new (192); */ /* ctx->c = mpi_new (192*2); */ /* } */ /* else if (ctx->nist_nbits == 384) */ /* { */ /* for (i=0; i < 10; i++) */ /* ctx->s[i] = mpi_new (384); */ /* ctx->c = mpi_new (384*2); */ /* } */ } static void ec_deinit (void *opaque) { mpi_ec_t ctx = opaque; int i; _gcry_mpi_barrett_free (ctx->t.p_barrett); /* Domain parameter. */ mpi_free (ctx->p); mpi_free (ctx->a); mpi_free (ctx->b); _gcry_mpi_point_release (ctx->G); mpi_free (ctx->n); mpi_free (ctx->h); /* The key. */ _gcry_mpi_point_release (ctx->Q); mpi_free (ctx->d); /* Private data of ec.c. */ mpi_free (ctx->t.two_inv_p); for (i=0; i< DIM(ctx->t.scratch); i++) mpi_free (ctx->t.scratch[i]); /* if (ctx->nist_nbits == 192) */ /* { */ /* for (i=0; i < 4; i++) */ /* mpi_free (ctx->s[i]); */ /* mpi_free (ctx->c); */ /* } */ /* else if (ctx->nist_nbits == 384) */ /* { */ /* for (i=0; i < 10; i++) */ /* mpi_free (ctx->s[i]); */ /* mpi_free (ctx->c); */ /* } */ } /* This function returns a new context for elliptic curve based on the field GF(p). P is the prime specifying this field, A is the first coefficient, B is the second coefficient, and MODEL is the model for the curve. This function is only used within Libgcrypt and not part of the public API. This context needs to be released using _gcry_mpi_ec_free. */ mpi_ec_t _gcry_mpi_ec_p_internal_new (enum gcry_mpi_ec_models model, enum ecc_dialects dialect, int flags, gcry_mpi_t p, gcry_mpi_t a, gcry_mpi_t b) { mpi_ec_t ctx; ctx = xcalloc (1, sizeof *ctx); ec_p_init (ctx, model, dialect, flags, p, a, b); return ctx; } /* This is a variant of _gcry_mpi_ec_p_internal_new which returns an public context and does some error checking on the supplied arguments. On success the new context is stored at R_CTX and 0 is returned; on error NULL is stored at R_CTX and an error code is returned. The context needs to be released using gcry_ctx_release. */ gpg_err_code_t _gcry_mpi_ec_p_new (gcry_ctx_t *r_ctx, enum gcry_mpi_ec_models model, enum ecc_dialects dialect, int flags, gcry_mpi_t p, gcry_mpi_t a, gcry_mpi_t b) { gcry_ctx_t ctx; mpi_ec_t ec; *r_ctx = NULL; if (!p || !a) return GPG_ERR_EINVAL; ctx = _gcry_ctx_alloc (CONTEXT_TYPE_EC, sizeof *ec, ec_deinit); if (!ctx) return gpg_err_code_from_syserror (); ec = _gcry_ctx_get_pointer (ctx, CONTEXT_TYPE_EC); ec_p_init (ec, model, dialect, flags, p, a, b); *r_ctx = ctx; return 0; } void _gcry_mpi_ec_free (mpi_ec_t ctx) { if (ctx) { ec_deinit (ctx); xfree (ctx); } } gcry_mpi_t _gcry_mpi_ec_get_mpi (const char *name, gcry_ctx_t ctx, int copy) { mpi_ec_t ec = _gcry_ctx_get_pointer (ctx, CONTEXT_TYPE_EC); return _gcry_ecc_get_mpi (name, ec, copy); } gcry_mpi_point_t _gcry_mpi_ec_get_point (const char *name, gcry_ctx_t ctx, int copy) { mpi_ec_t ec = _gcry_ctx_get_pointer (ctx, CONTEXT_TYPE_EC); (void)copy; /* Not used. */ return _gcry_ecc_get_point (name, ec); } gpg_err_code_t _gcry_mpi_ec_set_mpi (const char *name, gcry_mpi_t newvalue, gcry_ctx_t ctx) { mpi_ec_t ec = _gcry_ctx_get_pointer (ctx, CONTEXT_TYPE_EC); return _gcry_ecc_set_mpi (name, newvalue, ec); } gpg_err_code_t _gcry_mpi_ec_set_point (const char *name, gcry_mpi_point_t newvalue, gcry_ctx_t ctx) { mpi_ec_t ec = _gcry_ctx_get_pointer (ctx, CONTEXT_TYPE_EC); return _gcry_ecc_set_point (name, newvalue, ec); } /* Given an encoded point in the MPI VALUE and a context EC, decode * the point according to the context and store it in RESULT. On * error an error code is return but RESULT might have been changed. * If no context is given the function tries to decode VALUE by * assuming a 0x04 prefixed uncompressed encoding. */ gpg_err_code_t _gcry_mpi_ec_decode_point (mpi_point_t result, gcry_mpi_t value, mpi_ec_t ec) { gcry_err_code_t rc; if (ec && ec->dialect == ECC_DIALECT_ED25519) rc = _gcry_ecc_eddsa_decodepoint (value, ec, result, NULL, NULL); else if (ec && ec->model == MPI_EC_MONTGOMERY) rc = _gcry_ecc_mont_decodepoint (value, ec, result); else rc = _gcry_ecc_os2ec (result, value); return rc; } /* Compute the affine coordinates from the projective coordinates in POINT. Set them into X and Y. If one coordinate is not required, X or Y may be passed as NULL. CTX is the usual context. Returns: 0 on success or !0 if POINT is at infinity. */ int _gcry_mpi_ec_get_affine (gcry_mpi_t x, gcry_mpi_t y, mpi_point_t point, mpi_ec_t ctx) { if (!mpi_cmp_ui (point->z, 0)) return -1; switch (ctx->model) { case MPI_EC_WEIERSTRASS: /* Using Jacobian coordinates. */ { gcry_mpi_t z1, z2, z3; z1 = mpi_new (0); z2 = mpi_new (0); ec_invm (z1, point->z, ctx); /* z1 = z^(-1) mod p */ ec_mulm (z2, z1, z1, ctx); /* z2 = z^(-2) mod p */ if (x) ec_mulm (x, point->x, z2, ctx); if (y) { z3 = mpi_new (0); ec_mulm (z3, z2, z1, ctx); /* z3 = z^(-3) mod p */ ec_mulm (y, point->y, z3, ctx); mpi_free (z3); } mpi_free (z2); mpi_free (z1); } return 0; case MPI_EC_MONTGOMERY: { if (x) mpi_set (x, point->x); if (y) { log_fatal ("%s: Getting Y-coordinate on %s is not supported\n", "_gcry_mpi_ec_get_affine", "Montgomery"); return -1; } } return 0; case MPI_EC_EDWARDS: { gcry_mpi_t z; z = mpi_new (0); ec_invm (z, point->z, ctx); if (x) ec_mulm (x, point->x, z, ctx); if (y) ec_mulm (y, point->y, z, ctx); _gcry_mpi_release (z); } return 0; default: return -1; } } /* RESULT = 2 * POINT (Weierstrass version). */ static void dup_point_weierstrass (mpi_point_t result, mpi_point_t point, mpi_ec_t ctx) { #define x3 (result->x) #define y3 (result->y) #define z3 (result->z) #define t1 (ctx->t.scratch[0]) #define t2 (ctx->t.scratch[1]) #define t3 (ctx->t.scratch[2]) #define l1 (ctx->t.scratch[3]) #define l2 (ctx->t.scratch[4]) #define l3 (ctx->t.scratch[5]) if (!mpi_cmp_ui (point->y, 0) || !mpi_cmp_ui (point->z, 0)) { /* P_y == 0 || P_z == 0 => [1:1:0] */ mpi_set_ui (x3, 1); mpi_set_ui (y3, 1); mpi_set_ui (z3, 0); } else { if (ec_get_a_is_pminus3 (ctx)) /* Use the faster case. */ { /* L1 = 3(X - Z^2)(X + Z^2) */ /* T1: used for Z^2. */ /* T2: used for the right term. */ ec_pow2 (t1, point->z, ctx); ec_subm (l1, point->x, t1, ctx); ec_mulm (l1, l1, mpi_const (MPI_C_THREE), ctx); ec_addm (t2, point->x, t1, ctx); ec_mulm (l1, l1, t2, ctx); } else /* Standard case. */ { /* L1 = 3X^2 + aZ^4 */ /* T1: used for aZ^4. */ ec_pow2 (l1, point->x, ctx); ec_mulm (l1, l1, mpi_const (MPI_C_THREE), ctx); ec_powm (t1, point->z, mpi_const (MPI_C_FOUR), ctx); ec_mulm (t1, t1, ctx->a, ctx); ec_addm (l1, l1, t1, ctx); } /* Z3 = 2YZ */ ec_mulm (z3, point->y, point->z, ctx); ec_mul2 (z3, z3, ctx); /* L2 = 4XY^2 */ /* T2: used for Y2; required later. */ ec_pow2 (t2, point->y, ctx); ec_mulm (l2, t2, point->x, ctx); ec_mulm (l2, l2, mpi_const (MPI_C_FOUR), ctx); /* X3 = L1^2 - 2L2 */ /* T1: used for L2^2. */ ec_pow2 (x3, l1, ctx); ec_mul2 (t1, l2, ctx); ec_subm (x3, x3, t1, ctx); /* L3 = 8Y^4 */ /* T2: taken from above. */ ec_pow2 (t2, t2, ctx); ec_mulm (l3, t2, mpi_const (MPI_C_EIGHT), ctx); /* Y3 = L1(L2 - X3) - L3 */ ec_subm (y3, l2, x3, ctx); ec_mulm (y3, y3, l1, ctx); ec_subm (y3, y3, l3, ctx); } #undef x3 #undef y3 #undef z3 #undef t1 #undef t2 #undef t3 #undef l1 #undef l2 #undef l3 } /* RESULT = 2 * POINT (Montgomery version). */ static void dup_point_montgomery (mpi_point_t result, mpi_point_t point, mpi_ec_t ctx) { (void)result; (void)point; (void)ctx; log_fatal ("%s: %s not yet supported\n", "_gcry_mpi_ec_dup_point", "Montgomery"); } /* RESULT = 2 * POINT (Twisted Edwards version). */ static void dup_point_edwards (mpi_point_t result, mpi_point_t point, mpi_ec_t ctx) { #define X1 (point->x) #define Y1 (point->y) #define Z1 (point->z) #define X3 (result->x) #define Y3 (result->y) #define Z3 (result->z) #define B (ctx->t.scratch[0]) #define C (ctx->t.scratch[1]) #define D (ctx->t.scratch[2]) #define E (ctx->t.scratch[3]) #define F (ctx->t.scratch[4]) #define H (ctx->t.scratch[5]) #define J (ctx->t.scratch[6]) /* Compute: (X_3 : Y_3 : Z_3) = 2( X_1 : Y_1 : Z_1 ) */ /* B = (X_1 + Y_1)^2 */ ec_addm (B, X1, Y1, ctx); ec_pow2 (B, B, ctx); /* C = X_1^2 */ /* D = Y_1^2 */ ec_pow2 (C, X1, ctx); ec_pow2 (D, Y1, ctx); /* E = aC */ if (ctx->dialect == ECC_DIALECT_ED25519) mpi_sub (E, ctx->p, C); else ec_mulm (E, ctx->a, C, ctx); /* F = E + D */ ec_addm (F, E, D, ctx); /* H = Z_1^2 */ ec_pow2 (H, Z1, ctx); /* J = F - 2H */ ec_mul2 (J, H, ctx); ec_subm (J, F, J, ctx); /* X_3 = (B - C - D) · J */ ec_subm (X3, B, C, ctx); ec_subm (X3, X3, D, ctx); ec_mulm (X3, X3, J, ctx); /* Y_3 = F · (E - D) */ ec_subm (Y3, E, D, ctx); ec_mulm (Y3, Y3, F, ctx); /* Z_3 = F · J */ ec_mulm (Z3, F, J, ctx); #undef X1 #undef Y1 #undef Z1 #undef X3 #undef Y3 #undef Z3 #undef B #undef C #undef D #undef E #undef F #undef H #undef J } /* RESULT = 2 * POINT */ void _gcry_mpi_ec_dup_point (mpi_point_t result, mpi_point_t point, mpi_ec_t ctx) { switch (ctx->model) { case MPI_EC_WEIERSTRASS: dup_point_weierstrass (result, point, ctx); break; case MPI_EC_MONTGOMERY: dup_point_montgomery (result, point, ctx); break; case MPI_EC_EDWARDS: dup_point_edwards (result, point, ctx); break; } } /* RESULT = P1 + P2 (Weierstrass version).*/ static void add_points_weierstrass (mpi_point_t result, mpi_point_t p1, mpi_point_t p2, mpi_ec_t ctx) { #define x1 (p1->x ) #define y1 (p1->y ) #define z1 (p1->z ) #define x2 (p2->x ) #define y2 (p2->y ) #define z2 (p2->z ) #define x3 (result->x) #define y3 (result->y) #define z3 (result->z) #define l1 (ctx->t.scratch[0]) #define l2 (ctx->t.scratch[1]) #define l3 (ctx->t.scratch[2]) #define l4 (ctx->t.scratch[3]) #define l5 (ctx->t.scratch[4]) #define l6 (ctx->t.scratch[5]) #define l7 (ctx->t.scratch[6]) #define l8 (ctx->t.scratch[7]) #define l9 (ctx->t.scratch[8]) #define t1 (ctx->t.scratch[9]) #define t2 (ctx->t.scratch[10]) if ( (!mpi_cmp (x1, x2)) && (!mpi_cmp (y1, y2)) && (!mpi_cmp (z1, z2)) ) { /* Same point; need to call the duplicate function. */ _gcry_mpi_ec_dup_point (result, p1, ctx); } else if (!mpi_cmp_ui (z1, 0)) { /* P1 is at infinity. */ mpi_set (x3, p2->x); mpi_set (y3, p2->y); mpi_set (z3, p2->z); } else if (!mpi_cmp_ui (z2, 0)) { /* P2 is at infinity. */ mpi_set (x3, p1->x); mpi_set (y3, p1->y); mpi_set (z3, p1->z); } else { int z1_is_one = !mpi_cmp_ui (z1, 1); int z2_is_one = !mpi_cmp_ui (z2, 1); /* l1 = x1 z2^2 */ /* l2 = x2 z1^2 */ if (z2_is_one) mpi_set (l1, x1); else { ec_pow2 (l1, z2, ctx); ec_mulm (l1, l1, x1, ctx); } if (z1_is_one) mpi_set (l2, x2); else { ec_pow2 (l2, z1, ctx); ec_mulm (l2, l2, x2, ctx); } /* l3 = l1 - l2 */ ec_subm (l3, l1, l2, ctx); /* l4 = y1 z2^3 */ ec_powm (l4, z2, mpi_const (MPI_C_THREE), ctx); ec_mulm (l4, l4, y1, ctx); /* l5 = y2 z1^3 */ ec_powm (l5, z1, mpi_const (MPI_C_THREE), ctx); ec_mulm (l5, l5, y2, ctx); /* l6 = l4 - l5 */ ec_subm (l6, l4, l5, ctx); if (!mpi_cmp_ui (l3, 0)) { if (!mpi_cmp_ui (l6, 0)) { /* P1 and P2 are the same - use duplicate function. */ _gcry_mpi_ec_dup_point (result, p1, ctx); } else { /* P1 is the inverse of P2. */ mpi_set_ui (x3, 1); mpi_set_ui (y3, 1); mpi_set_ui (z3, 0); } } else { /* l7 = l1 + l2 */ ec_addm (l7, l1, l2, ctx); /* l8 = l4 + l5 */ ec_addm (l8, l4, l5, ctx); /* z3 = z1 z2 l3 */ ec_mulm (z3, z1, z2, ctx); ec_mulm (z3, z3, l3, ctx); /* x3 = l6^2 - l7 l3^2 */ ec_pow2 (t1, l6, ctx); ec_pow2 (t2, l3, ctx); ec_mulm (t2, t2, l7, ctx); ec_subm (x3, t1, t2, ctx); /* l9 = l7 l3^2 - 2 x3 */ ec_mul2 (t1, x3, ctx); ec_subm (l9, t2, t1, ctx); /* y3 = (l9 l6 - l8 l3^3)/2 */ ec_mulm (l9, l9, l6, ctx); ec_powm (t1, l3, mpi_const (MPI_C_THREE), ctx); /* fixme: Use saved value*/ ec_mulm (t1, t1, l8, ctx); ec_subm (y3, l9, t1, ctx); ec_mulm (y3, y3, ec_get_two_inv_p (ctx), ctx); } } #undef x1 #undef y1 #undef z1 #undef x2 #undef y2 #undef z2 #undef x3 #undef y3 #undef z3 #undef l1 #undef l2 #undef l3 #undef l4 #undef l5 #undef l6 #undef l7 #undef l8 #undef l9 #undef t1 #undef t2 } /* RESULT = P1 + P2 (Montgomery version).*/ static void add_points_montgomery (mpi_point_t result, mpi_point_t p1, mpi_point_t p2, mpi_ec_t ctx) { (void)result; (void)p1; (void)p2; (void)ctx; log_fatal ("%s: %s not yet supported\n", "_gcry_mpi_ec_add_points", "Montgomery"); } /* RESULT = P1 + P2 (Twisted Edwards version).*/ static void add_points_edwards (mpi_point_t result, mpi_point_t p1, mpi_point_t p2, mpi_ec_t ctx) { #define X1 (p1->x) #define Y1 (p1->y) #define Z1 (p1->z) #define X2 (p2->x) #define Y2 (p2->y) #define Z2 (p2->z) #define X3 (result->x) #define Y3 (result->y) #define Z3 (result->z) #define A (ctx->t.scratch[0]) #define B (ctx->t.scratch[1]) #define C (ctx->t.scratch[2]) #define D (ctx->t.scratch[3]) #define E (ctx->t.scratch[4]) #define F (ctx->t.scratch[5]) #define G (ctx->t.scratch[6]) #define tmp (ctx->t.scratch[7]) /* Compute: (X_3 : Y_3 : Z_3) = (X_1 : Y_1 : Z_1) + (X_2 : Y_2 : Z_3) */ /* A = Z1 · Z2 */ ec_mulm (A, Z1, Z2, ctx); /* B = A^2 */ ec_pow2 (B, A, ctx); /* C = X1 · X2 */ ec_mulm (C, X1, X2, ctx); /* D = Y1 · Y2 */ ec_mulm (D, Y1, Y2, ctx); /* E = d · C · D */ ec_mulm (E, ctx->b, C, ctx); ec_mulm (E, E, D, ctx); /* F = B - E */ ec_subm (F, B, E, ctx); /* G = B + E */ ec_addm (G, B, E, ctx); /* X_3 = A · F · ((X_1 + Y_1) · (X_2 + Y_2) - C - D) */ ec_addm (tmp, X1, Y1, ctx); ec_addm (X3, X2, Y2, ctx); ec_mulm (X3, X3, tmp, ctx); ec_subm (X3, X3, C, ctx); ec_subm (X3, X3, D, ctx); ec_mulm (X3, X3, F, ctx); ec_mulm (X3, X3, A, ctx); /* Y_3 = A · G · (D - aC) */ if (ctx->dialect == ECC_DIALECT_ED25519) { ec_addm (Y3, D, C, ctx); } else { ec_mulm (Y3, ctx->a, C, ctx); ec_subm (Y3, D, Y3, ctx); } ec_mulm (Y3, Y3, G, ctx); ec_mulm (Y3, Y3, A, ctx); /* Z_3 = F · G */ ec_mulm (Z3, F, G, ctx); #undef X1 #undef Y1 #undef Z1 #undef X2 #undef Y2 #undef Z2 #undef X3 #undef Y3 #undef Z3 #undef A #undef B #undef C #undef D #undef E #undef F #undef G #undef tmp } /* Compute a step of Montgomery Ladder (only use X and Z in the point). Inputs: P1, P2, and x-coordinate of DIF = P1 - P1. Outputs: PRD = 2 * P1 and SUM = P1 + P2. */ static void montgomery_ladder (mpi_point_t prd, mpi_point_t sum, mpi_point_t p1, mpi_point_t p2, gcry_mpi_t dif_x, mpi_ec_t ctx) { ec_addm (sum->x, p2->x, p2->z, ctx); ec_subm (p2->z, p2->x, p2->z, ctx); ec_addm (prd->x, p1->x, p1->z, ctx); ec_subm (p1->z, p1->x, p1->z, ctx); ec_mulm (p2->x, p1->z, sum->x, ctx); ec_mulm (p2->z, prd->x, p2->z, ctx); ec_pow2 (p1->x, prd->x, ctx); ec_pow2 (p1->z, p1->z, ctx); ec_addm (sum->x, p2->x, p2->z, ctx); ec_subm (p2->z, p2->x, p2->z, ctx); ec_mulm (prd->x, p1->x, p1->z, ctx); ec_subm (p1->z, p1->x, p1->z, ctx); ec_pow2 (sum->x, sum->x, ctx); ec_pow2 (sum->z, p2->z, ctx); ec_mulm (prd->z, p1->z, ctx->a, ctx); /* CTX->A: (a-2)/4 */ ec_mulm (sum->z, sum->z, dif_x, ctx); ec_addm (prd->z, p1->x, prd->z, ctx); ec_mulm (prd->z, prd->z, p1->z, ctx); } /* RESULT = P1 + P2 */ void _gcry_mpi_ec_add_points (mpi_point_t result, mpi_point_t p1, mpi_point_t p2, mpi_ec_t ctx) { switch (ctx->model) { case MPI_EC_WEIERSTRASS: add_points_weierstrass (result, p1, p2, ctx); break; case MPI_EC_MONTGOMERY: add_points_montgomery (result, p1, p2, ctx); break; case MPI_EC_EDWARDS: add_points_edwards (result, p1, p2, ctx); break; } } /* RESULT = P1 - P2 (Weierstrass version).*/ static void sub_points_weierstrass (mpi_point_t result, mpi_point_t p1, mpi_point_t p2, mpi_ec_t ctx) { (void)result; (void)p1; (void)p2; (void)ctx; log_fatal ("%s: %s not yet supported\n", "_gcry_mpi_ec_sub_points", "Weierstrass"); } /* RESULT = P1 - P2 (Montgomery version).*/ static void sub_points_montgomery (mpi_point_t result, mpi_point_t p1, mpi_point_t p2, mpi_ec_t ctx) { (void)result; (void)p1; (void)p2; (void)ctx; log_fatal ("%s: %s not yet supported\n", "_gcry_mpi_ec_sub_points", "Montgomery"); } /* RESULT = P1 - P2 (Twisted Edwards version).*/ static void sub_points_edwards (mpi_point_t result, mpi_point_t p1, mpi_point_t p2, mpi_ec_t ctx) { mpi_point_t p2i = _gcry_mpi_point_new (0); point_set (p2i, p2); mpi_sub (p2i->x, ctx->p, p2i->x); add_points_edwards (result, p1, p2i, ctx); _gcry_mpi_point_release (p2i); } /* RESULT = P1 - P2 */ void _gcry_mpi_ec_sub_points (mpi_point_t result, mpi_point_t p1, mpi_point_t p2, mpi_ec_t ctx) { switch (ctx->model) { case MPI_EC_WEIERSTRASS: sub_points_weierstrass (result, p1, p2, ctx); break; case MPI_EC_MONTGOMERY: sub_points_montgomery (result, p1, p2, ctx); break; case MPI_EC_EDWARDS: sub_points_edwards (result, p1, p2, ctx); break; } } /* Scalar point multiplication - the main function for ECC. If takes an integer SCALAR and a POINT as well as the usual context CTX. RESULT will be set to the resulting point. */ void _gcry_mpi_ec_mul_point (mpi_point_t result, gcry_mpi_t scalar, mpi_point_t point, mpi_ec_t ctx) { gcry_mpi_t x1, y1, z1, k, h, yy; unsigned int i, loops; mpi_point_struct p1, p2, p1inv; if (ctx->model == MPI_EC_EDWARDS || (ctx->model == MPI_EC_WEIERSTRASS && mpi_is_secure (scalar))) { /* Simple left to right binary method. GECC Algorithm 3.27 */ unsigned int nbits; int j; nbits = mpi_get_nbits (scalar); if (ctx->model == MPI_EC_WEIERSTRASS) { mpi_set_ui (result->x, 1); mpi_set_ui (result->y, 1); mpi_set_ui (result->z, 0); } else { mpi_set_ui (result->x, 0); mpi_set_ui (result->y, 1); mpi_set_ui (result->z, 1); } if (mpi_is_secure (scalar)) { /* If SCALAR is in secure memory we assume that it is the secret key we use constant time operation. */ mpi_point_struct tmppnt; point_init (&tmppnt); point_resize (result, ctx); point_resize (&tmppnt, ctx); for (j=nbits-1; j >= 0; j--) { _gcry_mpi_ec_dup_point (result, result, ctx); _gcry_mpi_ec_add_points (&tmppnt, result, point, ctx); point_swap_cond (result, &tmppnt, mpi_test_bit (scalar, j), ctx); } point_free (&tmppnt); } else { for (j=nbits-1; j >= 0; j--) { _gcry_mpi_ec_dup_point (result, result, ctx); if (mpi_test_bit (scalar, j)) _gcry_mpi_ec_add_points (result, result, point, ctx); } } return; } else if (ctx->model == MPI_EC_MONTGOMERY) { unsigned int nbits; int j; mpi_point_struct p1_, p2_; mpi_point_t q1, q2, prd, sum; unsigned long sw; /* Compute scalar point multiplication with Montgomery Ladder. Note that we don't use Y-coordinate in the points at all. RESULT->Y will be filled by zero. */ nbits = mpi_get_nbits (scalar); point_init (&p1); point_init (&p2); point_init (&p1_); point_init (&p2_); mpi_set_ui (p1.x, 1); mpi_free (p2.x); p2.x = mpi_copy (point->x); mpi_set_ui (p2.z, 1); point_resize (&p1, ctx); point_resize (&p2, ctx); point_resize (&p1_, ctx); point_resize (&p2_, ctx); q1 = &p1; q2 = &p2; prd = &p1_; sum = &p2_; for (j=nbits-1; j >= 0; j--) { mpi_point_t t; sw = mpi_test_bit (scalar, j); point_swap_cond (q1, q2, sw, ctx); montgomery_ladder (prd, sum, q1, q2, point->x, ctx); point_swap_cond (prd, sum, sw, ctx); t = q1; q1 = prd; prd = t; t = q2; q2 = sum; sum = t; } mpi_clear (result->y); sw = (nbits & 1); point_swap_cond (&p1, &p1_, sw, ctx); if (p1.z->nlimbs == 0) { mpi_set_ui (result->x, 1); mpi_set_ui (result->z, 0); } else { z1 = mpi_new (0); ec_invm (z1, p1.z, ctx); ec_mulm (result->x, p1.x, z1, ctx); mpi_set_ui (result->z, 1); mpi_free (z1); } point_free (&p1); point_free (&p2); point_free (&p1_); point_free (&p2_); return; } x1 = mpi_alloc_like (ctx->p); y1 = mpi_alloc_like (ctx->p); h = mpi_alloc_like (ctx->p); k = mpi_copy (scalar); yy = mpi_copy (point->y); if ( mpi_has_sign (k) ) { k->sign = 0; ec_invm (yy, yy, ctx); } if (!mpi_cmp_ui (point->z, 1)) { mpi_set (x1, point->x); mpi_set (y1, yy); } else { gcry_mpi_t z2, z3; z2 = mpi_alloc_like (ctx->p); z3 = mpi_alloc_like (ctx->p); ec_mulm (z2, point->z, point->z, ctx); ec_mulm (z3, point->z, z2, ctx); ec_invm (z2, z2, ctx); ec_mulm (x1, point->x, z2, ctx); ec_invm (z3, z3, ctx); ec_mulm (y1, yy, z3, ctx); mpi_free (z2); mpi_free (z3); } z1 = mpi_copy (mpi_const (MPI_C_ONE)); mpi_mul (h, k, mpi_const (MPI_C_THREE)); /* h = 3k */ loops = mpi_get_nbits (h); if (loops < 2) { /* If SCALAR is zero, the above mpi_mul sets H to zero and thus LOOPs will be zero. To avoid an underflow of I in the main loop we set LOOP to 2 and the result to (0,0,0). */ loops = 2; mpi_clear (result->x); mpi_clear (result->y); mpi_clear (result->z); } else { mpi_set (result->x, point->x); mpi_set (result->y, yy); mpi_set (result->z, point->z); } mpi_free (yy); yy = NULL; p1.x = x1; x1 = NULL; p1.y = y1; y1 = NULL; p1.z = z1; z1 = NULL; point_init (&p2); point_init (&p1inv); /* Invert point: y = p - y mod p */ point_set (&p1inv, &p1); ec_subm (p1inv.y, ctx->p, p1inv.y, ctx); for (i=loops-2; i > 0; i--) { _gcry_mpi_ec_dup_point (result, result, ctx); if (mpi_test_bit (h, i) == 1 && mpi_test_bit (k, i) == 0) { point_set (&p2, result); _gcry_mpi_ec_add_points (result, &p2, &p1, ctx); } if (mpi_test_bit (h, i) == 0 && mpi_test_bit (k, i) == 1) { point_set (&p2, result); _gcry_mpi_ec_add_points (result, &p2, &p1inv, ctx); } } point_free (&p1); point_free (&p2); point_free (&p1inv); mpi_free (h); mpi_free (k); } /* Return true if POINT is on the curve described by CTX. */ int _gcry_mpi_ec_curve_point (gcry_mpi_point_t point, mpi_ec_t ctx) { int res = 0; gcry_mpi_t x, y, w; x = mpi_new (0); y = mpi_new (0); w = mpi_new (0); switch (ctx->model) { case MPI_EC_WEIERSTRASS: { gcry_mpi_t xxx; if (_gcry_mpi_ec_get_affine (x, y, point, ctx)) goto leave; xxx = mpi_new (0); /* y^2 == x^3 + a·x + b */ ec_pow2 (y, y, ctx); ec_pow3 (xxx, x, ctx); ec_mulm (w, ctx->a, x, ctx); ec_addm (w, w, ctx->b, ctx); ec_addm (w, w, xxx, ctx); if (!mpi_cmp (y, w)) res = 1; _gcry_mpi_release (xxx); } break; case MPI_EC_MONTGOMERY: { #define xx y /* With Montgomery curve, only X-coordinate is valid. */ if (_gcry_mpi_ec_get_affine (x, NULL, point, ctx)) goto leave; /* The equation is: b * y^2 == x^3 + a · x^2 + x */ /* We check if right hand is quadratic residue or not by Euler's criterion. */ /* CTX->A has (a-2)/4 and CTX->B has b^-1 */ ec_mulm (w, ctx->a, mpi_const (MPI_C_FOUR), ctx); ec_addm (w, w, mpi_const (MPI_C_TWO), ctx); ec_mulm (w, w, x, ctx); ec_pow2 (xx, x, ctx); ec_addm (w, w, xx, ctx); ec_addm (w, w, mpi_const (MPI_C_ONE), ctx); ec_mulm (w, w, x, ctx); ec_mulm (w, w, ctx->b, ctx); #undef xx /* Compute Euler's criterion: w^(p-1)/2 */ #define p_minus1 y ec_subm (p_minus1, ctx->p, mpi_const (MPI_C_ONE), ctx); mpi_rshift (p_minus1, p_minus1, 1); ec_powm (w, w, p_minus1, ctx); res = !mpi_cmp_ui (w, 1); #undef p_minus1 } break; case MPI_EC_EDWARDS: { if (_gcry_mpi_ec_get_affine (x, y, point, ctx)) goto leave; /* a · x^2 + y^2 - 1 - b · x^2 · y^2 == 0 */ ec_pow2 (x, x, ctx); ec_pow2 (y, y, ctx); if (ctx->dialect == ECC_DIALECT_ED25519) mpi_sub (w, ctx->p, x); else ec_mulm (w, ctx->a, x, ctx); ec_addm (w, w, y, ctx); ec_subm (w, w, mpi_const (MPI_C_ONE), ctx); ec_mulm (x, x, y, ctx); ec_mulm (x, x, ctx->b, ctx); ec_subm (w, w, x, ctx); if (!mpi_cmp_ui (w, 0)) res = 1; } break; } leave: _gcry_mpi_release (w); _gcry_mpi_release (x); _gcry_mpi_release (y); return res; } diff --git a/mpi/mips3/README b/mpi/mips3/README index e94b2c74..4ba4546d 100644 --- a/mpi/mips3/README +++ b/mpi/mips3/README @@ -1,23 +1,23 @@ This directory contains mpn functions optimized for MIPS3. Example of processors that implement MIPS3 are R4000, R4400, R4600, R4700, and R8000. RELEVANT OPTIMIZATION ISSUES 1. On the R4000 and R4400, branches, both the plain and the "likely" ones, take 3 cycles to execute. (The fastest possible loop will take 4 cycles, because of the delay insn.) On the R4600, branches takes a single cycle - On the R8000, branches often take no noticable cycles, as they are + On the R8000, branches often take no noticeable cycles, as they are executed in a separate function unit.. 2. The R4000 and R4400 have a load latency of 4 cycles. 3. On the R4000 and R4400, multiplies take a data-dependent number of cycles, contrary to the SGI documentation. There seem to be 3 or 4 possible latencies. STATUS Good... diff --git a/random/random-drbg.c b/random/random-drbg.c index baaa65a2..7f66997b 100644 --- a/random/random-drbg.c +++ b/random/random-drbg.c @@ -1,2673 +1,2673 @@ /* random-drbg.c - Deterministic Random Bits Generator * Copyright 2014 Stephan Mueller * * DRBG: Deterministic Random Bits Generator * Based on NIST Recommended DRBG from NIST SP800-90A with the following * properties: * * CTR DRBG with DF with AES-128, AES-192, AES-256 cores * * Hash DRBG with DF with SHA-1, SHA-256, SHA-384, SHA-512 cores * * HMAC DRBG with DF with SHA-1, SHA-256, SHA-384, SHA-512 cores * * with and without prediction resistance * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, and the entire permission notice in its entirety, * including the disclaimer of warranties. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote * products derived from this software without specific prior * written permission. * * ALTERNATIVELY, this product may be distributed under the terms of * LGPLv2+, in which case the provisions of the LGPL are * required INSTEAD OF the above restrictions. (This clause is * necessary due to a potential bad interaction between the LGPL and * the restrictions contained in a BSD-style copyright.) * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF * WHICH ARE HEREBY DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * * * gcry_control GCRYCTL_DRBG_REINIT * ================================ * This control request re-initializes the DRBG completely, i.e. the entire * state of the DRBG is zeroized (with two exceptions listed in * GCRYCTL_DRBG_SET_ENTROPY). * * The control request takes the following values which influences how * the DRBG is re-initialized: * * - const char *flagstr * * This variable specifies the DRBG type to be used for the next * initialization. If set to NULL, the previous DRBG type is * used for the initialization. If not NULL a space separated * list of tokens with associated flag values is expected which * are ORed to form the mandatory flags of the requested DRBG * strength and cipher type. Optionally, the prediction * resistance flag can be ORed into the flags variable. * * | String token | Flag value | * |--------------+------------------------| * | aes | DRBG_CTRAES | * | serpent | DRBG_CTRSERPENT | * | twofish | DRBG_CTRTWOFISH | * | sha1 | DRBG_HASHSHA1 | * | sha256 | DRBG_HASHSHA256 | * | sha512 | DRBG_HASHSHA512 | * | hmac | DRBG_HMAC | * | sym128 | DRBG_SYM128 | * | sym192 | DRBG_SYM192 | * | sym256 | DRBG_SYM256 | * | pr | DRBG_PREDICTION_RESIST | * * For example: * * - CTR-DRBG with AES-128 without prediction resistance: * "aes sym128" * - HMAC-DRBG with SHA-512 with prediction resistance: * "hmac sha512 pr" * * - gcry_buffer_t *pers * * NULL terminated array with personalization strings to be used * for initialization. * * - int npers * * Size of PERS. * * - void *guard * * A value of NULL must be passed for this. * * The variable of flags is independent from the pers/perslen variables. If * flags is set to 0 and perslen is set to 0, the current DRBG type is * completely reset without using a personalization string. * * DRBG Usage * ========== * The SP 800-90A DRBG allows the user to specify a personalization string * for initialization as well as an additional information string for each * random number request. The following code fragments show how a caller * uses the API to use the full functionality of the DRBG. * * Usage without any additional data * --------------------------------- * gcry_randomize(outbuf, OUTLEN, GCRY_STRONG_RANDOM); * * * Usage with personalization string during initialization * ------------------------------------------------------- * drbg_string_t pers; * char personalization[11] = "some-string"; * * drbg_string_fill(&pers, personalization, strlen(personalization)); * // The reset completely re-initializes the DRBG with the provided * // personalization string without changing the DRBG type * ret = gcry_control(GCRYCTL_DRBG_REINIT, 0, &pers); * gcry_randomize(outbuf, OUTLEN, GCRY_STRONG_RANDOM); * * * Usage with additional information string during random number request * --------------------------------------------------------------------- * drbg_string_t addtl; * char addtl_string[11] = "some-string"; * * drbg_string_fill(&addtl, addtl_string, strlen(addtl_string)); * // The following call is a wrapper to gcry_randomize() and returns * // the same error codes. * gcry_randomize_drbg(outbuf, OUTLEN, GCRY_STRONG_RANDOM, &addtl); * * * Usage with personalization and additional information strings * ------------------------------------------------------------- * Just mix both scenarios above. * * * Switch the DRBG type to some other type * --------------------------------------- * // Switch to CTR DRBG AES-128 without prediction resistance * ret = gcry_control(GCRYCTL_DRBG_REINIT, DRBG_NOPR_CTRAES128, NULL); * gcry_randomize(outbuf, OUTLEN, GCRY_STRONG_RANDOM); */ #include #include #include #include #include "g10lib.h" #include "random.h" #include "rand-internal.h" #include "../cipher/bufhelp.h" /****************************************************************** * Constants ******************************************************************/ /* * DRBG flags bitmasks * * 31 (B) 28 19 (A) 0 * +-+-+-+--------+---+-----------+-----+ * |~|~|u|~~~~~~~~| 3 | 2 | 1 | * +-+-+-+--------+- -+-----------+-----+ * ctl flg| |drbg use selection flags * */ /* Internal state control flags (B) */ #define DRBG_PREDICTION_RESIST ((u32)1<<28) /* CTR type modifiers (A.1)*/ #define DRBG_CTRAES ((u32)1<<0) #define DRBG_CTRSERPENT ((u32)1<<1) #define DRBG_CTRTWOFISH ((u32)1<<2) #define DRBG_CTR_MASK (DRBG_CTRAES | DRBG_CTRSERPENT \ | DRBG_CTRTWOFISH) /* HASH type modifiers (A.2)*/ #define DRBG_HASHSHA1 ((u32)1<<4) #define DRBG_HASHSHA224 ((u32)1<<5) #define DRBG_HASHSHA256 ((u32)1<<6) #define DRBG_HASHSHA384 ((u32)1<<7) #define DRBG_HASHSHA512 ((u32)1<<8) #define DRBG_HASH_MASK (DRBG_HASHSHA1 | DRBG_HASHSHA224 \ | DRBG_HASHSHA256 | DRBG_HASHSHA384 \ | DRBG_HASHSHA512) /* type modifiers (A.3)*/ #define DRBG_HMAC ((u32)1<<12) #define DRBG_SYM128 ((u32)1<<13) #define DRBG_SYM192 ((u32)1<<14) #define DRBG_SYM256 ((u32)1<<15) #define DRBG_TYPE_MASK (DRBG_HMAC | DRBG_SYM128 | DRBG_SYM192 \ | DRBG_SYM256) #define DRBG_CIPHER_MASK (DRBG_CTR_MASK | DRBG_HASH_MASK \ | DRBG_TYPE_MASK) #define DRBG_PR_CTRAES128 (DRBG_PREDICTION_RESIST | DRBG_CTRAES | DRBG_SYM128) #define DRBG_PR_CTRAES192 (DRBG_PREDICTION_RESIST | DRBG_CTRAES | DRBG_SYM192) #define DRBG_PR_CTRAES256 (DRBG_PREDICTION_RESIST | DRBG_CTRAES | DRBG_SYM256) #define DRBG_NOPR_CTRAES128 (DRBG_CTRAES | DRBG_SYM128) #define DRBG_NOPR_CTRAES192 (DRBG_CTRAES | DRBG_SYM192) #define DRBG_NOPR_CTRAES256 (DRBG_CTRAES | DRBG_SYM256) #define DRBG_PR_HASHSHA1 (DRBG_PREDICTION_RESIST | DRBG_HASHSHA1) #define DRBG_PR_HASHSHA256 (DRBG_PREDICTION_RESIST | DRBG_HASHSHA256) #define DRBG_PR_HASHSHA384 (DRBG_PREDICTION_RESIST | DRBG_HASHSHA384) #define DRBG_PR_HASHSHA512 (DRBG_PREDICTION_RESIST | DRBG_HASHSHA512) #define DRBG_NOPR_HASHSHA1 (DRBG_HASHSHA1) #define DRBG_NOPR_HASHSHA256 (DRBG_HASHSHA256) #define DRBG_NOPR_HASHSHA384 (DRBG_HASHSHA384) #define DRBG_NOPR_HASHSHA512 (DRBG_HASHSHA512) #define DRBG_PR_HMACSHA1 (DRBG_PREDICTION_RESIST | DRBG_HASHSHA1 \ | DRBG_HMAC) #define DRBG_PR_HMACSHA256 (DRBG_PREDICTION_RESIST | DRBG_HASHSHA256 \ | DRBG_HMAC) #define DRBG_PR_HMACSHA384 (DRBG_PREDICTION_RESIST | DRBG_HASHSHA384 \ | DRBG_HMAC) #define DRBG_PR_HMACSHA512 (DRBG_PREDICTION_RESIST | DRBG_HASHSHA512 \ | DRBG_HMAC) #define DRBG_NOPR_HMACSHA1 (DRBG_HASHSHA1 | DRBG_HMAC) #define DRBG_NOPR_HMACSHA256 (DRBG_HASHSHA256 | DRBG_HMAC) #define DRBG_NOPR_HMACSHA384 (DRBG_HASHSHA384 | DRBG_HMAC) #define DRBG_NOPR_HMACSHA512 (DRBG_HASHSHA512 | DRBG_HMAC) /* The default DRGB type. */ #define DRBG_DEFAULT_TYPE DRBG_NOPR_HMACSHA256 /****************************************************************** * Common data structures ******************************************************************/ /* * SP800-90A requires the concatenation of different data. To avoid copying * buffers around or allocate additional memory, the following data structure * is used to point to the original memory with its size. In addition, it * is used to build a linked list. The linked list defines the concatenation * of individual buffers. The order of memory block referenced in that * linked list determines the order of concatenation. */ struct drbg_string_s { const unsigned char *buf; size_t len; struct drbg_string_s *next; }; typedef struct drbg_string_s drbg_string_t; /* DRBG input data structure for DRBG generate with additional * information string. */ struct drbg_gen_s { unsigned char *outbuf; /* output buffer for random numbers */ unsigned int outlen; /* size of output buffer */ drbg_string_t *addtl; /* input buffer for * additional information string */ }; typedef struct drbg_gen_s drbg_gen_t; /* Forward declaration of the state object pointer. */ struct drbg_state_s; typedef struct drbg_state_s *drbg_state_t; struct drbg_core_s { u32 flags; /* flags for the cipher */ ushort statelen; /* maximum state length */ ushort blocklen_bytes; /* block size of output in bytes */ int backend_cipher; /* libgcrypt backend cipher */ }; struct drbg_state_ops_s { gpg_err_code_t (*update) (drbg_state_t drbg, drbg_string_t *seed, int reseed); gpg_err_code_t (*generate) (drbg_state_t drbg, unsigned char *buf, unsigned int buflen, drbg_string_t *addtl); gpg_err_code_t (*crypto_init) (drbg_state_t drbg); void (*crypto_fini) (drbg_state_t drbg); }; struct drbg_test_data_s { drbg_string_t *testentropy; /* TEST PARAMETER: test entropy */ int fail_seed_source:1; /* If set, the seed function will * return an error. */ }; /* This state object keeps the state of an DRBG instance. */ struct drbg_state_s { unsigned char *V; /* internal state 10.1.1.1 1a) */ unsigned char *C; /* hash: static value 10.1.1.1 1b) * hmac / ctr: key */ size_t reseed_ctr; /* Number of RNG requests since last reseed -- * 10.1.1.1 1c) */ unsigned char *scratchpad; /* some memory the DRBG can use for its * operation -- allocated during init */ void *priv_data; /* Cipher handle */ gcry_cipher_hd_t ctr_handle; /* CTR mode cipher handle */ #define DRBG_CTR_NULL_LEN 128 unsigned char *ctr_null; /* CTR mode zero buffer */ int seeded:1; /* DRBG fully seeded? */ int pr:1; /* Prediction resistance enabled? */ /* Taken from libgcrypt ANSI X9.31 DRNG: We need to keep track of the * process which did the initialization so that we can detect a fork. * The volatile modifier is required so that the compiler does not * optimize it away in case the getpid function is badly attributed. */ pid_t seed_init_pid; const struct drbg_state_ops_s *d_ops; const struct drbg_core_s *core; struct drbg_test_data_s *test_data; }; enum drbg_prefixes { DRBG_PREFIX0 = 0x00, DRBG_PREFIX1, DRBG_PREFIX2, DRBG_PREFIX3 }; #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) /*************************************************************** * Global variables ***************************************************************/ /* Global state variable holding the current instance of the DRBG. */ static drbg_state_t drbg_state; /* This is the lock variable we use to serialize access to this RNG. */ GPGRT_LOCK_DEFINE(drbg_lock_var); /*************************************************************** * Backend cipher definitions available to DRBG ***************************************************************/ static const struct drbg_core_s drbg_cores[] = { /* Hash DRBGs */ {DRBG_HASHSHA1, 55, 20, GCRY_MD_SHA1}, {DRBG_HASHSHA256, 55, 32, GCRY_MD_SHA256}, {DRBG_HASHSHA384, 111, 48, GCRY_MD_SHA384}, {DRBG_HASHSHA512, 111, 64, GCRY_MD_SHA512}, /* HMAC DRBGs */ {DRBG_HASHSHA1 | DRBG_HMAC, 20, 20, GCRY_MD_SHA1}, {DRBG_HASHSHA256 | DRBG_HMAC, 32, 32, GCRY_MD_SHA256}, {DRBG_HASHSHA384 | DRBG_HMAC, 48, 48, GCRY_MD_SHA384}, {DRBG_HASHSHA512 | DRBG_HMAC, 64, 64, GCRY_MD_SHA512}, /* block ciphers */ {DRBG_CTRAES | DRBG_SYM128, 32, 16, GCRY_CIPHER_AES128}, {DRBG_CTRAES | DRBG_SYM192, 40, 16, GCRY_CIPHER_AES192}, {DRBG_CTRAES | DRBG_SYM256, 48, 16, GCRY_CIPHER_AES256} }; static gpg_err_code_t drbg_hash_init (drbg_state_t drbg); static gpg_err_code_t drbg_hmac_init (drbg_state_t drbg); static gpg_err_code_t drbg_hmac_setkey (drbg_state_t drbg, const unsigned char *key); static void drbg_hash_fini (drbg_state_t drbg); static byte *drbg_hash (drbg_state_t drbg, const drbg_string_t *buf); static gpg_err_code_t drbg_sym_init (drbg_state_t drbg); static void drbg_sym_fini (drbg_state_t drbg); static gpg_err_code_t drbg_sym_setkey (drbg_state_t drbg, const unsigned char *key); static gpg_err_code_t drbg_sym (drbg_state_t drbg, unsigned char *outval, const drbg_string_t *buf); static gpg_err_code_t drbg_sym_ctr (drbg_state_t drbg, const unsigned char *inbuf, unsigned int inbuflen, unsigned char *outbuf, unsigned int outbuflen); /****************************************************************** ****************************************************************** ****************************************************************** * Generic DRBG code ****************************************************************** ****************************************************************** ******************************************************************/ /****************************************************************** * Generic helper functions ******************************************************************/ #if 0 #define dbg(x) do { log_debug x; } while(0) #else #define dbg(x) #endif /* * Parse a string of flags and store the flag values at R_FLAGS. * Return 0 on success. */ static gpg_err_code_t parse_flag_string (const char *string, u32 *r_flags) { struct { const char *name; u32 flag; } table[] = { { "aes", DRBG_CTRAES }, { "serpent", DRBG_CTRSERPENT }, { "twofish", DRBG_CTRTWOFISH }, { "sha1", DRBG_HASHSHA1 }, { "sha256", DRBG_HASHSHA256 }, { "sha512", DRBG_HASHSHA512 }, { "hmac", DRBG_HMAC }, { "sym128", DRBG_SYM128 }, { "sym192", DRBG_SYM192 }, { "sym256", DRBG_SYM256 }, { "pr", DRBG_PREDICTION_RESIST } }; *r_flags = 0; if (string) { char **tl; const char *s; int i, j; tl = _gcry_strtokenize (string, NULL); if (!tl) return gpg_err_code_from_syserror (); for (i=0; (s=tl[i]); i++) { for (j=0; j < DIM (table); j++) if (!strcmp (s, table[j].name)) { *r_flags |= table[j].flag; break; } if (!(j < DIM (table))) { xfree (tl); return GPG_ERR_INV_FLAG; } } xfree (tl); } return 0; } static inline void drbg_string_fill (drbg_string_t *string, const unsigned char *buf, size_t len) { string->buf = buf; string->len = len; string->next = NULL; } static inline ushort drbg_statelen (drbg_state_t drbg) { if (drbg && drbg->core) return drbg->core->statelen; return 0; } static inline ushort drbg_blocklen (drbg_state_t drbg) { if (drbg && drbg->core) return drbg->core->blocklen_bytes; return 0; } static inline ushort drbg_keylen (drbg_state_t drbg) { if (drbg && drbg->core) return (drbg->core->statelen - drbg->core->blocklen_bytes); return 0; } static inline size_t drbg_max_request_bytes (void) { /* SP800-90A requires the limit 2**19 bits, but we return bytes */ return (1 << 16); } static inline size_t drbg_max_addtl (void) { /* SP800-90A requires 2**35 bytes additional info str / pers str */ #ifdef __LP64__ return (1UL << 35); #else /* * SP800-90A allows smaller maximum numbers to be returned -- we * return SIZE_MAX - 1 to allow the verification of the enforcement * of this value in drbg_healthcheck_sanity. */ return (SIZE_MAX - 1); #endif } static inline size_t drbg_max_requests (void) { /* SP800-90A requires 2**48 maximum requests before reseeding */ #ifdef __LP64__ return (1UL << 48); #else return SIZE_MAX; #endif } /* * Return strength of DRBG according to SP800-90A section 8.4 * * flags: DRBG flags reference * * Return: normalized strength value or 32 as a default to counter * programming errors */ static inline unsigned short drbg_sec_strength (u32 flags) { if ((flags & DRBG_HASHSHA1) || (flags & DRBG_SYM128)) return 16; else if (flags & DRBG_SYM192) return 24; else if ((flags & DRBG_SYM256) || (flags & DRBG_HASHSHA256) || (flags & DRBG_HASHSHA384) || (flags & DRBG_HASHSHA512)) return 32; else return 32; } static void drbg_add_buf (unsigned char *dst, size_t dstlen, unsigned char *add, size_t addlen) { /* implied: dstlen > addlen */ unsigned char *dstptr, *addptr; unsigned int remainder = 0; size_t len = addlen; dstptr = dst + (dstlen - 1); addptr = add + (addlen - 1); while (len) { remainder += *dstptr + *addptr; *dstptr = remainder & 0xff; remainder >>= 8; len--; dstptr--; addptr--; } len = dstlen - addlen; while (len && remainder > 0) { remainder = *dstptr + 1; *dstptr = remainder & 0xff; remainder >>= 8; len--; dstptr--; } } /* Helper variables for read_cb(). * * The _gcry_rnd*_gather_random interface does not allow to provide a * data pointer. Thus we need to use a global variable for * communication. However, the then required locking is anyway a good * idea because it does not make sense to have several readers of (say * /dev/random). It is easier to serve them one after the other. */ static unsigned char *read_cb_buffer; /* The buffer. */ static size_t read_cb_size; /* Size of the buffer. */ static size_t read_cb_len; /* Used length. */ /* Callback for generating seed from kernel device. */ static void drbg_read_cb (const void *buffer, size_t length, enum random_origins origin) { const unsigned char *p = buffer; (void) origin; gcry_assert (read_cb_buffer); /* Note that we need to protect against gatherers returning more * than the requested bytes (e.g. rndw32). */ while (length-- && read_cb_len < read_cb_size) read_cb_buffer[read_cb_len++] = *p++; } static inline int drbg_get_entropy (drbg_state_t drbg, unsigned char *buffer, size_t len) { int rc = 0; /* Perform testing as defined in 11.3.2 */ if (drbg->test_data && drbg->test_data->fail_seed_source) return -1; read_cb_buffer = buffer; read_cb_size = len; read_cb_len = 0; #if USE_RNDLINUX rc = _gcry_rndlinux_gather_random (drbg_read_cb, 0, len, GCRY_VERY_STRONG_RANDOM); #elif USE_RNDUNIX rc = _gcry_rndunix_gather_random (drbg_read_cb, 0, len, GCRY_VERY_STRONG_RANDOM); #elif USE_RNDW32 do { rc = _gcry_rndw32_gather_random (drbg_read_cb, 0, len, GCRY_VERY_STRONG_RANDOM); } while (rc >= 0 && read_cb_len < read_cb_size); #else rc = -1; #endif return rc; } /****************************************************************** * CTR DRBG callback functions ******************************************************************/ /* BCC function for CTR DRBG as defined in 10.4.3 */ static gpg_err_code_t drbg_ctr_bcc (drbg_state_t drbg, unsigned char *out, const unsigned char *key, drbg_string_t *in) { gpg_err_code_t ret = GPG_ERR_GENERAL; drbg_string_t *curr = in; size_t inpos = curr->len; const unsigned char *pos = curr->buf; drbg_string_t data; drbg_string_fill (&data, out, drbg_blocklen (drbg)); /* 10.4.3 step 1 */ memset (out, 0, drbg_blocklen (drbg)); ret = drbg_sym_setkey(drbg, key); if (ret) return ret; /* 10.4.3 step 2 / 4 */ while (inpos) { short cnt = 0; /* 10.4.3 step 4.1 */ for (cnt = 0; cnt < drbg_blocklen (drbg); cnt++) { out[cnt] ^= *pos; pos++; inpos--; /* the following branch implements the linked list * iteration. If we are at the end of the current data * set, we have to start using the next data set if * available -- the inpos value always points to the * current byte and will be zero if we have processed * the last byte of the last linked list member */ if (0 == inpos) { curr = curr->next; if (NULL != curr) { pos = curr->buf; inpos = curr->len; } else { inpos = 0; break; } } } /* 10.4.3 step 4.2 */ ret = drbg_sym (drbg, out, &data); if (ret) return ret; /* 10.4.3 step 2 */ } return 0; } /* * scratchpad usage: drbg_ctr_update is interlinked with drbg_ctr_df * (and drbg_ctr_bcc, but this function does not need any temporary buffers), * the scratchpad is used as follows: * drbg_ctr_update: * temp * start: drbg->scratchpad * length: drbg_statelen(drbg) + drbg_blocklen(drbg) * note: the cipher writing into this variable works * blocklen-wise. Now, when the statelen is not a multiple * of blocklen, the generateion loop below "spills over" * by at most blocklen. Thus, we need to give sufficient * memory. * df_data * start: drbg->scratchpad + * drbg_statelen(drbg) + * drbg_blocklen(drbg) * length: drbg_statelen(drbg) * * drbg_ctr_df: * pad * start: df_data + drbg_statelen(drbg) * length: drbg_blocklen(drbg) * iv * start: pad + drbg_blocklen(drbg) * length: drbg_blocklen(drbg) * temp * start: iv + drbg_blocklen(drbg) * length: drbg_satelen(drbg) + drbg_blocklen(drbg) * note: temp is the buffer that the BCC function operates * on. BCC operates blockwise. drbg_statelen(drbg) * is sufficient when the DRBG state length is a multiple * of the block size. For AES192 (and maybe other ciphers) * this is not correct and the length for temp is * insufficient (yes, that also means for such ciphers, * the final output of all BCC rounds are truncated). * Therefore, add drbg_blocklen(drbg) to cover all * possibilities. */ /* Derivation Function for CTR DRBG as defined in 10.4.2 */ static gpg_err_code_t drbg_ctr_df (drbg_state_t drbg, unsigned char *df_data, size_t bytes_to_return, drbg_string_t *addtl) { gpg_err_code_t ret = GPG_ERR_GENERAL; unsigned char L_N[8]; /* S3 is input */ drbg_string_t S1, S2, S4, cipherin; drbg_string_t *tempstr = addtl; unsigned char *pad = df_data + drbg_statelen (drbg); unsigned char *iv = pad + drbg_blocklen (drbg); unsigned char *temp = iv + drbg_blocklen (drbg); size_t padlen = 0; unsigned int templen = 0; /* 10.4.2 step 7 */ unsigned int i = 0; /* 10.4.2 step 8 */ const unsigned char *K = (unsigned char *) "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f"; unsigned char *X; size_t generated_len = 0; size_t inputlen = 0; memset (pad, 0, drbg_blocklen (drbg)); memset (iv, 0, drbg_blocklen (drbg)); memset (temp, 0, drbg_statelen (drbg)); /* 10.4.2 step 1 is implicit as we work byte-wise */ /* 10.4.2 step 2 */ if ((512 / 8) < bytes_to_return) return GPG_ERR_INV_ARG; /* 10.4.2 step 2 -- calculate the entire length of all input data */ for (; NULL != tempstr; tempstr = tempstr->next) inputlen += tempstr->len; buf_put_be32 (&L_N[0], inputlen); /* 10.4.2 step 3 */ buf_put_be32 (&L_N[4], bytes_to_return); /* 10.4.2 step 5: length is size of L_N, input_string, one byte, padding */ padlen = (inputlen + sizeof (L_N) + 1) % (drbg_blocklen (drbg)); /* wrap the padlen appropriately */ if (padlen) padlen = drbg_blocklen (drbg) - padlen; /* pad / padlen contains the 0x80 byte and the following zero bytes, so * add one for byte for 0x80 */ padlen++; pad[0] = 0x80; /* 10.4.2 step 4 -- first fill the linked list and then order it */ drbg_string_fill (&S1, iv, drbg_blocklen (drbg)); drbg_string_fill (&S2, L_N, sizeof (L_N)); drbg_string_fill (&S4, pad, padlen); S1.next = &S2; S2.next = addtl; /* Splice in addtl between S2 and S4 -- we place S4 at the end of the * input data chain. As this code is only triggered when addtl is not * NULL, no NULL checks are necessary.*/ tempstr = addtl; while (tempstr->next) tempstr = tempstr->next; tempstr->next = &S4; /* 10.4.2 step 9 */ while (templen < (drbg_keylen (drbg) + (drbg_blocklen (drbg)))) { /* 10.4.2 step 9.1 - the padding is implicit as the buffer * holds zeros after allocation -- even the increment of i * is irrelevant as the increment remains within length of i */ buf_put_be32 (iv, i); /* 10.4.2 step 9.2 -- BCC and concatenation with temp */ ret = drbg_ctr_bcc (drbg, temp + templen, K, &S1); if (ret) goto out; /* 10.4.2 step 9.3 */ i++; templen += drbg_blocklen (drbg); } /* 10.4.2 step 11 */ /* implicit key len with seedlen - blocklen according to table 3 */ X = temp + (drbg_keylen (drbg)); drbg_string_fill (&cipherin, X, drbg_blocklen (drbg)); /* 10.4.2 step 12: overwriting of outval */ /* 10.4.2 step 13 */ ret = drbg_sym_setkey(drbg, temp); if (ret) goto out; while (generated_len < bytes_to_return) { short blocklen = 0; /* 10.4.2 step 13.1 */ /* the truncation of the key length is implicit as the key * is only drbg_blocklen in size -- check for the implementation * of the cipher function callback */ ret = drbg_sym (drbg, X, &cipherin); if (ret) goto out; blocklen = (drbg_blocklen (drbg) < (bytes_to_return - generated_len)) ? drbg_blocklen (drbg) : (bytes_to_return - generated_len); /* 10.4.2 step 13.2 and 14 */ memcpy (df_data + generated_len, X, blocklen); generated_len += blocklen; } ret = 0; out: memset (iv, 0, drbg_blocklen (drbg)); memset (temp, 0, drbg_statelen (drbg)); memset (pad, 0, drbg_blocklen (drbg)); return ret; } /* * Update function of CTR DRBG as defined in 10.2.1.2 * * The reseed variable has an enhanced meaning compared to the update * functions of the other DRBGs as follows: * 0 => initial seed from initialization * 1 => reseed via drbg_seed * 2 => first invocation from drbg_ctr_update when addtl is present. In * this case, the df_data scratchpad is not deleted so that it is * available for another calls to prevent calling the DF function * again. * 3 => second invocation from drbg_ctr_update. When the update function * was called with addtl, the df_data memory already contains the * DFed addtl information and we do not need to call DF again. */ static gpg_err_code_t drbg_ctr_update (drbg_state_t drbg, drbg_string_t *addtl, int reseed) { gpg_err_code_t ret = GPG_ERR_GENERAL; /* 10.2.1.2 step 1 */ unsigned char *temp = drbg->scratchpad; unsigned char *df_data = drbg->scratchpad + drbg_statelen (drbg) + drbg_blocklen (drbg); unsigned char prefix = DRBG_PREFIX1; memset (temp, 0, drbg_statelen (drbg) + drbg_blocklen (drbg)); if (3 > reseed) memset (df_data, 0, drbg_statelen (drbg)); if (!reseed) { /* * The DRBG uses the CTR mode of the underlying AES cipher. The * CTR mode increments the counter value after the AES operation * but SP800-90A requires that the counter is incremented before * the AES operation. Hence, we increment it at the time we set * it by one. */ drbg_add_buf (drbg->V, drbg_blocklen (drbg), &prefix, 1); ret = _gcry_cipher_setkey (drbg->ctr_handle, drbg->C, drbg_keylen (drbg)); if (ret) goto out; } /* 10.2.1.3.2 step 2 and 10.2.1.4.2 step 2 */ if (addtl && 0 < addtl->len) { ret = drbg_ctr_df (drbg, df_data, drbg_statelen (drbg), addtl); if (ret) goto out; } ret = drbg_sym_ctr (drbg, df_data, drbg_statelen(drbg), temp, drbg_statelen(drbg)); if (ret) goto out; /* 10.2.1.2 step 5 */ ret = _gcry_cipher_setkey (drbg->ctr_handle, temp, drbg_keylen (drbg)); if (ret) goto out; /* 10.2.1.2 step 6 */ memcpy (drbg->V, temp + drbg_keylen (drbg), drbg_blocklen (drbg)); /* See above: increment counter by one to compensate timing of CTR op */ drbg_add_buf (drbg->V, drbg_blocklen (drbg), &prefix, 1); ret = 0; out: memset (temp, 0, drbg_statelen (drbg) + drbg_blocklen (drbg)); if (2 != reseed) memset (df_data, 0, drbg_statelen (drbg)); return ret; } /* * scratchpad use: drbg_ctr_update is called independently from * drbg_ctr_extract_bytes. Therefore, the scratchpad is reused */ /* Generate function of CTR DRBG as defined in 10.2.1.5.2 */ static gpg_err_code_t drbg_ctr_generate (drbg_state_t drbg, unsigned char *buf, unsigned int buflen, drbg_string_t *addtl) { gpg_err_code_t ret = 0; memset (drbg->scratchpad, 0, drbg_blocklen (drbg)); /* 10.2.1.5.2 step 2 */ if (addtl && 0 < addtl->len) { addtl->next = NULL; ret = drbg_ctr_update (drbg, addtl, 2); if (ret) return ret; } /* 10.2.1.5.2 step 4.1 */ ret = drbg_sym_ctr (drbg, drbg->ctr_null, DRBG_CTR_NULL_LEN, buf, buflen); if (ret) goto out; /* 10.2.1.5.2 step 6 */ if (addtl) addtl->next = NULL; ret = drbg_ctr_update (drbg, addtl, 3); out: return ret; } static struct drbg_state_ops_s drbg_ctr_ops = { drbg_ctr_update, drbg_ctr_generate, drbg_sym_init, drbg_sym_fini, }; /****************************************************************** * HMAC DRBG callback functions ******************************************************************/ static gpg_err_code_t drbg_hmac_update (drbg_state_t drbg, drbg_string_t *seed, int reseed) { gpg_err_code_t ret = GPG_ERR_GENERAL; int i = 0; drbg_string_t seed1, seed2, cipherin; if (!reseed) { /* 10.1.2.3 step 2 already implicitly covered with * the initial memset(0) of drbg->C */ memset (drbg->V, 1, drbg_statelen (drbg)); ret = drbg_hmac_setkey (drbg, drbg->C); if (ret) return ret; } /* build linked list which implements the concatenation and fill * first part*/ drbg_string_fill (&seed1, drbg->V, drbg_statelen (drbg)); /* buffer will be filled in for loop below with one byte */ drbg_string_fill (&seed2, NULL, 1); seed1.next = &seed2; /* seed may be NULL */ seed2.next = seed; drbg_string_fill (&cipherin, drbg->V, drbg_statelen (drbg)); /* we execute two rounds of V/K massaging */ for (i = 2; 0 < i; i--) { byte *retval; /* first round uses 0x0, second 0x1 */ unsigned char prefix = DRBG_PREFIX0; if (1 == i) prefix = DRBG_PREFIX1; /* 10.1.2.2 step 1 and 4 -- concatenation and HMAC for key */ seed2.buf = &prefix; retval = drbg_hash (drbg, &seed1); ret = drbg_hmac_setkey (drbg, retval); if (ret) return ret; /* 10.1.2.2 step 2 and 5 -- HMAC for V */ retval = drbg_hash (drbg, &cipherin); memcpy(drbg->V, retval, drbg_blocklen (drbg)); /* 10.1.2.2 step 3 */ if (!seed || 0 == seed->len) return ret; } return 0; } /* generate function of HMAC DRBG as defined in 10.1.2.5 */ static gpg_err_code_t drbg_hmac_generate (drbg_state_t drbg, unsigned char *buf, unsigned int buflen, drbg_string_t *addtl) { gpg_err_code_t ret = 0; unsigned int len = 0; drbg_string_t data; /* 10.1.2.5 step 2 */ if (addtl && 0 < addtl->len) { addtl->next = NULL; ret = drbg_hmac_update (drbg, addtl, 1); if (ret) return ret; } drbg_string_fill (&data, drbg->V, drbg_statelen (drbg)); while (len < buflen) { unsigned int outlen = 0; /* 10.1.2.5 step 4.1 */ byte *retval = drbg_hash (drbg, &data); memcpy(drbg->V, retval, drbg_blocklen (drbg)); outlen = (drbg_blocklen (drbg) < (buflen - len)) ? drbg_blocklen (drbg) : (buflen - len); /* 10.1.2.5 step 4.2 */ memcpy (buf + len, drbg->V, outlen); len += outlen; } /* 10.1.2.5 step 6 */ if (addtl) addtl->next = NULL; ret = drbg_hmac_update (drbg, addtl, 1); return ret; } static struct drbg_state_ops_s drbg_hmac_ops = { drbg_hmac_update, drbg_hmac_generate, drbg_hmac_init, drbg_hash_fini, }; /****************************************************************** * Hash DRBG callback functions ******************************************************************/ /* * scratchpad usage: as drbg_hash_update and drbg_hash_df are used * interlinked, the scratchpad is used as follows: * drbg_hash_update * start: drbg->scratchpad * length: drbg_statelen(drbg) * drbg_hash_df: * start: drbg->scratchpad + drbg_statelen(drbg) * length: drbg_blocklen(drbg) */ /* Derivation Function for Hash DRBG as defined in 10.4.1 */ static gpg_err_code_t drbg_hash_df (drbg_state_t drbg, unsigned char *outval, size_t outlen, drbg_string_t *entropy) { size_t len = 0; unsigned char input[5]; drbg_string_t data1; /* 10.4.1 step 3 */ input[0] = 1; buf_put_be32 (&input[1], (outlen * 8)); /* 10.4.1 step 4.1 -- concatenation of data for input into hash */ drbg_string_fill (&data1, input, 5); data1.next = entropy; /* 10.4.1 step 4 */ while (len < outlen) { short blocklen = 0; /* 10.4.1 step 4.1 */ byte *retval = drbg_hash (drbg, &data1); /* 10.4.1 step 4.2 */ input[0]++; blocklen = (drbg_blocklen (drbg) < (outlen - len)) ? drbg_blocklen (drbg) : (outlen - len); memcpy (outval + len, retval, blocklen); len += blocklen; } return 0; } /* update function for Hash DRBG as defined in 10.1.1.2 / 10.1.1.3 */ static gpg_err_code_t drbg_hash_update (drbg_state_t drbg, drbg_string_t *seed, int reseed) { gpg_err_code_t ret = 0; drbg_string_t data1, data2; unsigned char *V = drbg->scratchpad; unsigned char prefix = DRBG_PREFIX1; memset (drbg->scratchpad, 0, drbg_statelen (drbg)); if (!seed) return GPG_ERR_INV_ARG; if (reseed) { /* 10.1.1.3 step 1: string length is concatenation of * 1 byte, V and seed (which is concatenated entropy/addtl * input) */ memcpy (V, drbg->V, drbg_statelen (drbg)); drbg_string_fill (&data1, &prefix, 1); drbg_string_fill (&data2, V, drbg_statelen (drbg)); data1.next = &data2; data2.next = seed; } else { drbg_string_fill (&data1, seed->buf, seed->len); data1.next = seed->next; } /* 10.1.1.2 / 10.1.1.3 step 2 and 3 */ ret = drbg_hash_df (drbg, drbg->V, drbg_statelen (drbg), &data1); if (ret) goto out; /* 10.1.1.2 / 10.1.1.3 step 4 -- concatenation */ prefix = DRBG_PREFIX0; drbg_string_fill (&data1, &prefix, 1); drbg_string_fill (&data2, drbg->V, drbg_statelen (drbg)); data1.next = &data2; /* 10.1.1.2 / 10.1.1.3 step 4 -- df operation */ ret = drbg_hash_df (drbg, drbg->C, drbg_statelen (drbg), &data1); out: memset (drbg->scratchpad, 0, drbg_statelen (drbg)); return ret; } /* Processing of additional information string for Hash DRBG. */ static gpg_err_code_t drbg_hash_process_addtl (drbg_state_t drbg, drbg_string_t *addtl) { drbg_string_t data1, data2; drbg_string_t *data3; unsigned char prefix = DRBG_PREFIX2; byte *retval; /* 10.1.1.4 step 2 */ if (!addtl || 0 == addtl->len) return 0; /* 10.1.1.4 step 2a -- concatenation */ drbg_string_fill (&data1, &prefix, 1); drbg_string_fill (&data2, drbg->V, drbg_statelen (drbg)); data3 = addtl; data1.next = &data2; data2.next = data3; data3->next = NULL; /* 10.1.1.4 step 2a -- cipher invocation */ retval = drbg_hash (drbg, &data1); /* 10.1.1.4 step 2b */ drbg_add_buf (drbg->V, drbg_statelen (drbg), retval, drbg_blocklen (drbg)); return 0; } /* * Hashgen defined in 10.1.1.4 */ static gpg_err_code_t drbg_hash_hashgen (drbg_state_t drbg, unsigned char *buf, unsigned int buflen) { unsigned int len = 0; unsigned char *src = drbg->scratchpad; drbg_string_t data; unsigned char prefix = DRBG_PREFIX1; /* 10.1.1.4 step hashgen 2 */ memcpy (src, drbg->V, drbg_statelen (drbg)); drbg_string_fill (&data, src, drbg_statelen (drbg)); while (len < buflen) { unsigned int outlen = 0; /* 10.1.1.4 step hashgen 4.1 */ byte *retval = drbg_hash (drbg, &data); outlen = (drbg_blocklen (drbg) < (buflen - len)) ? drbg_blocklen (drbg) : (buflen - len); /* 10.1.1.4 step hashgen 4.2 */ memcpy (buf + len, retval, outlen); len += outlen; /* 10.1.1.4 hashgen step 4.3 */ if (len < buflen) drbg_add_buf (src, drbg_statelen (drbg), &prefix, 1); } memset (drbg->scratchpad, 0, drbg_statelen (drbg)); return 0; } /* Generate function for Hash DRBG as defined in 10.1.1.4 */ static gpg_err_code_t drbg_hash_generate (drbg_state_t drbg, unsigned char *buf, unsigned int buflen, drbg_string_t *addtl) { gpg_err_code_t ret; unsigned char prefix = DRBG_PREFIX3; drbg_string_t data1, data2; byte *retval; union { unsigned char req[8]; u64 req_int; } u; /* 10.1.1.4 step 2 */ ret = drbg_hash_process_addtl (drbg, addtl); if (ret) return ret; /* 10.1.1.4 step 3 -- invocation of the Hashgen function defined in * 10.1.1.4 */ ret = drbg_hash_hashgen (drbg, buf, buflen); if (ret) return ret; /* 10.1.1.4 step 4 */ drbg_string_fill (&data1, &prefix, 1); drbg_string_fill (&data2, drbg->V, drbg_statelen (drbg)); data1.next = &data2; /* this is the value H as documented in 10.1.1.4 */ retval = drbg_hash (drbg, &data1); /* 10.1.1.4 step 5 */ drbg_add_buf (drbg->V, drbg_statelen (drbg), retval, drbg_blocklen (drbg)); drbg_add_buf (drbg->V, drbg_statelen (drbg), drbg->C, drbg_statelen (drbg)); u.req_int = be_bswap64 (drbg->reseed_ctr); drbg_add_buf (drbg->V, drbg_statelen (drbg), u.req, sizeof (u.req)); return ret; } /* * scratchpad usage: as update and generate are used isolated, both * can use the scratchpad */ static struct drbg_state_ops_s drbg_hash_ops = { drbg_hash_update, drbg_hash_generate, drbg_hash_init, drbg_hash_fini, }; /****************************************************************** * Functions common for DRBG implementations ******************************************************************/ /* * Seeding or reseeding of the DRBG * * @drbg: DRBG state struct * @pers: personalization / additional information buffer * @reseed: 0 for initial seed process, 1 for reseeding * * return: * 0 on success * error value otherwise */ static gpg_err_code_t drbg_seed (drbg_state_t drbg, drbg_string_t *pers, int reseed) { gpg_err_code_t ret = 0; unsigned char *entropy = NULL; size_t entropylen = 0; drbg_string_t data1; /* 9.1 / 9.2 / 9.3.1 step 3 */ if (pers && pers->len > (drbg_max_addtl ())) { dbg (("DRBG: personalization string too long %lu\n", pers->len)); return GPG_ERR_INV_ARG; } if (drbg->test_data && drbg->test_data->testentropy) { drbg_string_fill (&data1, drbg->test_data->testentropy->buf, drbg->test_data->testentropy->len); dbg (("DRBG: using test entropy\n")); } else { /* Gather entropy equal to the security strength of the DRBG. * With a derivation function, a nonce is required in addition * to the entropy. A nonce must be at least 1/2 of the security * strength of the DRBG in size. Thus, entropy * nonce is 3/2 * of the strength. The consideration of a nonce is only * applicable during initial seeding. */ entropylen = drbg_sec_strength (drbg->core->flags); if (!entropylen) return GPG_ERR_GENERAL; if (0 == reseed) /* make sure we round up strength/2 in * case it is not divisible by 2 */ entropylen = ((entropylen + 1) / 2) * 3; dbg (("DRBG: (re)seeding with %lu bytes of entropy\n", entropylen)); entropy = xcalloc_secure (1, entropylen); if (!entropy) return GPG_ERR_ENOMEM; ret = drbg_get_entropy (drbg, entropy, entropylen); if (ret) goto out; drbg_string_fill (&data1, entropy, entropylen); } /* concatenation of entropy with personalization str / addtl input) * the variable pers is directly handed by the caller, check its * contents whether it is appropriate */ if (pers && pers->buf && 0 < pers->len && NULL == pers->next) { data1.next = pers; dbg (("DRBG: using personalization string\n")); } ret = drbg->d_ops->update (drbg, &data1, reseed); dbg (("DRBG: state updated with seed\n")); if (ret) goto out; drbg->seeded = 1; /* 10.1.1.2 / 10.1.1.3 step 5 */ drbg->reseed_ctr = 1; out: xfree (entropy); return ret; } /************************************************************************* * Exported interfaces. *************************************************************************/ /* * DRBG generate function as required by SP800-90A - this function * generates random numbers * * @drbg DRBG state handle * @buf Buffer where to store the random numbers -- the buffer must already * be pre-allocated by caller * @buflen Length of output buffer - this value defines the number of random * bytes pulled from DRBG * @addtl Additional input that is mixed into state, may be NULL -- note * the entropy is pulled by the DRBG internally unconditionally * as defined in SP800-90A. The additional input is mixed into * the state in addition to the pulled entropy. * * return: Generated number of bytes. */ static gpg_err_code_t drbg_generate (drbg_state_t drbg, unsigned char *buf, unsigned int buflen, drbg_string_t *addtl) { gpg_err_code_t ret = GPG_ERR_INV_ARG; if (0 == buflen || !buf) { dbg (("DRBG: no buffer provided\n")); return ret; } if (addtl && NULL == addtl->buf && 0 < addtl->len) { dbg (("DRBG: wrong format of additional information\n")); return ret; } /* 9.3.1 step 2 */ if (buflen > (drbg_max_request_bytes ())) { dbg (("DRBG: requested random numbers too large %u\n", buflen)); return ret; } /* 9.3.1 step 3 is implicit with the chosen DRBG */ /* 9.3.1 step 4 */ if (addtl && addtl->len > (drbg_max_addtl ())) { dbg (("DRBG: additional information string too long %lu\n", addtl->len)); return ret; } /* 9.3.1 step 5 is implicit with the chosen DRBG */ /* 9.3.1 step 6 and 9 supplemented by 9.3.2 step c -- the spec is a * bit convoluted here, we make it simpler */ if ((drbg_max_requests ()) < drbg->reseed_ctr) drbg->seeded = 0; if (drbg->pr || !drbg->seeded) { dbg (("DRBG: reseeding before generation (prediction resistance: %s, state %s)\n", drbg->pr ? "true" : "false", drbg->seeded ? "seeded" : "unseeded")); /* 9.3.1 steps 7.1 through 7.3 */ ret = drbg_seed (drbg, addtl, 1); if (ret) return ret; /* 9.3.1 step 7.4 */ addtl = NULL; } if (addtl && addtl->buf) { dbg (("DRBG: using additional information string\n")); } /* 9.3.1 step 8 and 10 */ ret = drbg->d_ops->generate (drbg, buf, buflen, addtl); /* 10.1.1.4 step 6, 10.1.2.5 step 7, 10.2.1.5.2 step 7 */ drbg->reseed_ctr++; if (ret) return ret; /* 11.3.3 -- re-perform self tests after some generated random * numbers, the chosen value after which self test is performed * is arbitrary, but it should be reasonable */ /* Here we do not perform the self tests because of the following * reasons: it is mathematically impossible that the initial self tests * were successfully and the following are not. If the initial would * pass and the following would not, the system integrity is violated. * In this case, the entire system operation is questionable and it * is unlikely that the integrity violation only affects to the * correct operation of the DRBG. */ #if 0 if (drbg->reseed_ctr && !(drbg->reseed_ctr % 4096)) { dbg (("DRBG: start to perform self test\n")); ret = drbg_healthcheck (); if (ret) { log_fatal (("DRBG: self test failed\n")); return ret; } else { dbg (("DRBG: self test successful\n")); } } #endif return ret; } /* * Wrapper around drbg_generate which can pull arbitrary long strings * from the DRBG without hitting the maximum request limitation. * * Parameters: see drbg_generate * Return codes: see drbg_generate -- if one drbg_generate request fails, * the entire drbg_generate_long request fails */ static gpg_err_code_t drbg_generate_long (drbg_state_t drbg, unsigned char *buf, unsigned int buflen, drbg_string_t *addtl) { gpg_err_code_t ret = 0; unsigned int slice = 0; unsigned char *buf_p = buf; unsigned len = 0; do { unsigned int chunk = 0; slice = ((buflen - len) / drbg_max_request_bytes ()); chunk = slice ? drbg_max_request_bytes () : (buflen - len); ret = drbg_generate (drbg, buf_p, chunk, addtl); if (ret) return ret; buf_p += chunk; len += chunk; } while (slice > 0 && (len < buflen)); return ret; } /* * DRBG uninstantiate function as required by SP800-90A - this function * frees all buffers and the DRBG handle * * @drbg DRBG state handle * * return * 0 on success */ static gpg_err_code_t drbg_uninstantiate (drbg_state_t drbg) { if (!drbg) return GPG_ERR_INV_ARG; drbg->d_ops->crypto_fini(drbg); xfree (drbg->V); drbg->V = NULL; xfree (drbg->C); drbg->C = NULL; drbg->reseed_ctr = 0; xfree (drbg->scratchpad); drbg->scratchpad = NULL; drbg->seeded = 0; drbg->pr = 0; drbg->seed_init_pid = 0; return 0; } /* * DRBG instantiation function as required by SP800-90A - this function * sets up the DRBG handle, performs the initial seeding and all sanity * checks required by SP800-90A * * @drbg memory of state -- if NULL, new memory is allocated * @pers Personalization string that is mixed into state, may be NULL -- note * the entropy is pulled by the DRBG internally unconditionally * as defined in SP800-90A. The additional input is mixed into * the state in addition to the pulled entropy. * @coreref reference to core * @flags Flags defining the requested DRBG type and cipher type. The flags * are defined in drbg.h and may be XORed. Beware, if you XOR multiple * cipher types together, the code picks the core on a first come first * serve basis as it iterates through the available cipher cores and * uses the one with the first match. The minimum required flags are: * cipher type flag * * return * 0 on success * error value otherwise */ static gpg_err_code_t drbg_instantiate (drbg_state_t drbg, drbg_string_t *pers, int coreref, int pr) { gpg_err_code_t ret = GPG_ERR_ENOMEM; unsigned int sb_size = 0; if (!drbg) return GPG_ERR_INV_ARG; dbg (("DRBG: Initializing DRBG core %d with prediction resistance %s\n", coreref, pr ? "enabled" : "disabled")); drbg->core = &drbg_cores[coreref]; drbg->pr = pr; drbg->seeded = 0; if (drbg->core->flags & DRBG_HMAC) drbg->d_ops = &drbg_hmac_ops; else if (drbg->core->flags & DRBG_HASH_MASK) drbg->d_ops = &drbg_hash_ops; else if (drbg->core->flags & DRBG_CTR_MASK) drbg->d_ops = &drbg_ctr_ops; else return GPG_ERR_GENERAL; /* 9.1 step 1 is implicit with the selected DRBG type -- see * drbg_sec_strength() */ /* 9.1 step 2 is implicit as caller can select prediction resistance * and the flag is copied into drbg->flags -- * all DRBG types support prediction resistance */ /* 9.1 step 4 is implicit in drbg_sec_strength */ ret = drbg->d_ops->crypto_init(drbg); if (ret) goto err; drbg->V = xcalloc_secure (1, drbg_statelen (drbg)); if (!drbg->V) goto fini; drbg->C = xcalloc_secure (1, drbg_statelen (drbg)); if (!drbg->C) goto fini; /* scratchpad is only generated for CTR and Hash */ if (drbg->core->flags & DRBG_HMAC) sb_size = 0; else if (drbg->core->flags & DRBG_CTR_MASK) sb_size = drbg_statelen (drbg) + drbg_blocklen (drbg) + /* temp */ drbg_statelen (drbg) + /* df_data */ drbg_blocklen (drbg) + /* pad */ drbg_blocklen (drbg) + /* iv */ drbg_statelen (drbg) + drbg_blocklen (drbg); /* temp */ else sb_size = drbg_statelen (drbg); if (0 < sb_size) { drbg->scratchpad = xcalloc_secure (1, sb_size); if (!drbg->scratchpad) goto fini; } dbg (("DRBG: state allocated with scratchpad size %u bytes\n", sb_size)); /* 9.1 step 6 through 11 */ ret = drbg_seed (drbg, pers, 0); if (ret) goto fini; dbg (("DRBG: core %d %s prediction resistance successfully initialized\n", coreref, pr ? "with" : "without")); return 0; fini: drbg->d_ops->crypto_fini(drbg); err: drbg_uninstantiate (drbg); return ret; } /* * DRBG reseed function as required by SP800-90A * * @drbg DRBG state handle * @addtl Additional input that is mixed into state, may be NULL -- note * the entropy is pulled by the DRBG internally unconditionally * as defined in SP800-90A. The additional input is mixed into * the state in addition to the pulled entropy. * * return * 0 on success * error value otherwise */ static gpg_err_code_t drbg_reseed (drbg_state_t drbg,drbg_string_t *addtl) { gpg_err_code_t ret = 0; ret = drbg_seed (drbg, addtl, 1); return ret; } /****************************************************************** * Libgcrypt integration code. ******************************************************************/ /*************************************************** * Libgcrypt backend functions to the RNG API code. ***************************************************/ static inline void drbg_lock (void) { gpg_err_code_t ec; ec = gpgrt_lock_lock (&drbg_lock_var); if (ec) log_fatal ("failed to acquire the RNG lock: %s\n", gpg_strerror (ec)); } static inline void drbg_unlock (void) { gpg_err_code_t ec; ec = gpgrt_lock_unlock (&drbg_lock_var); if (ec) log_fatal ("failed to release the RNG lock: %s\n", gpg_strerror (ec)); } /* Basic initialization is required to initialize mutexes and do a few checks on the implementation. */ static void basic_initialization (void) { static int initialized; if (initialized) return; initialized = 1; /* Make sure that we are still using the values we have traditionally used for the random levels. */ gcry_assert (GCRY_WEAK_RANDOM == 0 && GCRY_STRONG_RANDOM == 1 && GCRY_VERY_STRONG_RANDOM == 2); } /****** helper functions where lock must be held by caller *****/ /* Check whether given flags are known to point to an applicable DRBG */ static gpg_err_code_t drbg_algo_available (u32 flags, int *coreref) { int i = 0; for (i = 0; ARRAY_SIZE (drbg_cores) > i; i++) { if ((drbg_cores[i].flags & DRBG_CIPHER_MASK) == (flags & DRBG_CIPHER_MASK)) { *coreref = i; return 0; } } return GPG_ERR_GENERAL; } static gpg_err_code_t _drbg_init_internal (u32 flags, drbg_string_t *pers) { static u32 oldflags; gpg_err_code_t ret = 0; int coreref = 0; int pr = 0; /* If a caller provides 0 as flags, use the flags of the previous * initialization, otherwise use the current flags and remember them * for the next invocation. If no flag is given and no global state * is set this is the first initialization and we set the default * type. */ if (!flags && !drbg_state) flags = oldflags = DRBG_DEFAULT_TYPE; else if (!flags) flags = oldflags; else oldflags = flags; ret = drbg_algo_available (flags, &coreref); if (ret) return ret; if (drbg_state) { drbg_uninstantiate (drbg_state); } else { drbg_state = xtrycalloc_secure (1, sizeof *drbg_state); if (!drbg_state) return gpg_err_code_from_syserror (); } if (flags & DRBG_PREDICTION_RESIST) pr = 1; ret = drbg_instantiate (drbg_state, pers, coreref, pr); if (ret) fips_signal_error ("DRBG cannot be initialized"); else drbg_state->seed_init_pid = getpid (); return ret; } /************* calls available to common RNG code **************/ /* * Initialize one DRBG invoked by the libgcrypt API */ void _gcry_rngdrbg_inititialize (int full) { basic_initialization (); if (!full) return; drbg_lock (); if (!drbg_state) _drbg_init_internal (0, NULL); drbg_unlock (); } /* * Backend handler function for GCRYCTL_DRBG_REINIT * * Select a different DRBG type and initialize it. * Function checks whether requested DRBG type exists and returns an error in * case it does not. In case of an error, the previous instantiated DRBG is * left untouched and alive. Thus, in case of an error, a DRBG is always * available, even if it is not the chosen one. * * Re-initialization will be performed in any case regardless whether flags * or personalization string are set. * * If flags is NULL, do not change current DRBG. If PERS is NULL and * NPERS is 0, re-initialize without personalization string. If PERS * is not NULL NPERS must be one and PERS and the first ietm from the * bufer is take as personalization string. */ gpg_err_code_t _gcry_rngdrbg_reinit (const char *flagstr, gcry_buffer_t *pers, int npers) { gpg_err_code_t ret; unsigned int flags; /* If PERS is not given we expect NPERS to be zero; if given we expect a one-item array. */ if ((!pers && npers) || (pers && npers != 1)) return GPG_ERR_INV_ARG; ret = parse_flag_string (flagstr, &flags); if (!ret) { dbg (("DRBG: reinitialize internal DRBG state with flags %u\n", flags)); drbg_lock (); if (pers) { drbg_string_t persbuf; drbg_string_fill (&persbuf, (const unsigned char *)pers[0].data + pers[0].off, pers[0].len); ret = _drbg_init_internal (flags, &persbuf); } else ret = _drbg_init_internal (flags, NULL); drbg_unlock (); } return ret; } /* Try to close the FDs of the random gather module. This is * currently only implemented for rndlinux. */ void _gcry_rngdrbg_close_fds (void) { #if USE_RNDLINUX drbg_lock (); _gcry_rndlinux_gather_random (NULL, 0, 0, 0); drbg_unlock (); #endif } /* Print some statistics about the RNG. */ void _gcry_rngdrbg_dump_stats (void) { /* Not yet implemented. */ /* Maybe dumping of reseed counter? */ } /* This function returns true if no real RNG is available or the * quality of the RNG has been degraded for test purposes. */ int _gcry_rngdrbg_is_faked (void) { return 0; /* Faked random is not allowed. */ } /* Add BUFLEN bytes from BUF to the internal random pool. QUALITY * should be in the range of 0..100 to indicate the goodness of the * entropy added, or -1 for goodness not known. */ gcry_error_t _gcry_rngdrbg_add_bytes (const void *buf, size_t buflen, int quality) { gpg_err_code_t ret = 0; drbg_string_t seed; (void) quality; _gcry_rngdrbg_inititialize (1); /* Auto-initialize if needed */ if (!drbg_state) return GPG_ERR_GENERAL; drbg_string_fill (&seed, (unsigned char *) buf, buflen); drbg_lock (); ret = drbg_reseed (drbg_state, &seed); drbg_unlock (); return ret; } /* This function is to be used for all types of random numbers, including * nonces */ void _gcry_rngdrbg_randomize (void *buffer, size_t length, enum gcry_random_level level) { (void) level; _gcry_rngdrbg_inititialize (1); /* Auto-initialize if needed */ drbg_lock (); if (!drbg_state) { fips_signal_error ("DRBG is not initialized"); goto bailout; } /* As reseeding changes the entire state of the DRBG, including any * key, either a re-init or a reseed is sufficient for a fork */ if (drbg_state->seed_init_pid != getpid ()) { /* We are in a child of us. Perform a reseeding. */ if (drbg_reseed (drbg_state, NULL)) { fips_signal_error ("reseeding upon fork failed"); log_fatal ("severe error getting random\n"); goto bailout; } } /* potential integer overflow is covered by drbg_generate which * ensures that length cannot overflow an unsigned int */ if (0 < length) { if (!buffer) goto bailout; if (drbg_generate_long (drbg_state, buffer, (unsigned int) length, NULL)) log_fatal ("No random numbers generated\n"); } else { drbg_gen_t *data = (drbg_gen_t *)buffer; /* catch NULL pointer */ if (!data || !data->outbuf) { fips_signal_error ("No output buffer provided"); goto bailout; } if (drbg_generate_long (drbg_state, data->outbuf, data->outlen, data->addtl)) log_fatal ("No random numbers generated\n"); } bailout: drbg_unlock (); return; } /*************************************************************** * Self-test code ***************************************************************/ /* * Test vectors from * http://csrc.nist.gov/groups/STM/cavp/documents/drbg/drbgtestvectors.zip */ struct gcry_drbg_test_vector drbg_test_pr[] = { { /* .flags = */ "sha256 pr" /* DRBG_PR_HASHSHA256 */, /* .entropy = */ (unsigned char *) "\x5d\xf2\x14\xbc\xf6\xb5\x4e\x0b\xf0\x0d\x6f\x2d" "\xe2\x01\x66\x7b\xd0\xa4\x73\xa4\x21\xdd\xb0\xc0" "\x51\x79\x09\xf4\xea\xa9\x08\xfa\xa6\x67\xe0\xe1" "\xd1\x88\xa8\xad\xee\x69\x74\xb3\x55\x06\x9b\xf6", /* .entropylen = */ 48, /* .entpra = */ (unsigned char *) "\xef\x48\x06\xa2\xc2\x45\xf1\x44\xfa\x34\x2c\xeb" "\x8d\x78\x3c\x09\x8f\x34\x72\x20\xf2\xe7\xfd\x13" "\x76\x0a\xf6\xdc\x3c\xf5\xc0\x15", /* .entprb = */ (unsigned char *) "\x4b\xbe\xe5\x24\xed\x6a\x2d\x0c\xdb\x73\x5e\x09" "\xf9\xad\x67\x7c\x51\x47\x8b\x6b\x30\x2a\xc6\xde" "\x76\xaa\x55\x04\x8b\x0a\x72\x95", /* .entprlen = */ 32, /* .addtla = */ (unsigned char *) "\xbe\x13\xdb\x2a\xe9\xa8\xfe\x09\x97\xe1\xce\x5d" "\xe8\xbb\xc0\x7c\x4f\xcb\x62\x19\x3f\x0f\xd2\xad" "\xa9\xd0\x1d\x59\x02\xc4\xff\x70", /* .addtlb = */ (unsigned char *) "\x6f\x96\x13\xe2\xa7\xf5\x6c\xfe\xdf\x66\xe3\x31" "\x63\x76\xbf\x20\x27\x06\x49\xf1\xf3\x01\x77\x41" "\x9f\xeb\xe4\x38\xfe\x67\x00\xcd", /* .addtllen = */ 32, /* .pers = */ NULL, /* .perslen = */ 0, /* .expected = */ (unsigned char *) "\x3b\x14\x71\x99\xa1\xda\xa0\x42\xe6\xc8\x85\x32" "\x70\x20\x32\x53\x9a\xbe\xd1\x1e\x15\xef\xfb\x4c" "\x25\x6e\x19\x3a\xf0\xb9\xcb\xde\xf0\x3b\xc6\x18" "\x4d\x85\x5a\x9b\xf1\xe3\xc2\x23\x03\x93\x08\xdb" "\xa7\x07\x4b\x33\x78\x40\x4d\xeb\x24\xf5\x6e\x81" "\x4a\x1b\x6e\xa3\x94\x52\x43\xb0\xaf\x2e\x21\xf4" "\x42\x46\x8e\x90\xed\x34\x21\x75\xea\xda\x67\xb6" "\xe4\xf6\xff\xc6\x31\x6c\x9a\x5a\xdb\xb3\x97\x13" "\x09\xd3\x20\x98\x33\x2d\x6d\xd7\xb5\x6a\xa8\xa9" "\x9a\x5b\xd6\x87\x52\xa1\x89\x2b\x4b\x9c\x64\x60" "\x50\x47\xa3\x63\x81\x16\xaf\x19", /* .expectedlen = */ 128, /* .entropyreseed = */ NULL, /* .entropyreseed_len = */ 0, /* .addtl_reseed = */ NULL, /* .addtl_reseed_len = */ 0 }, { /* flags = */ "hmac sha256 pr" /* DRBG_PR_HMACSHA256 */, /* .entropy = */ (unsigned char *) "\x13\x54\x96\xfc\x1b\x7d\x28\xf3\x18\xc9\xa7\x89" "\xb6\xb3\xc8\x72\xac\x00\xd4\x59\x36\x25\x05\xaf" "\xa5\xdb\x96\xcb\x3c\x58\x46\x87\xa5\xaa\xbf\x20" "\x3b\xfe\x23\x0e\xd1\xc7\x41\x0f\x3f\xc9\xb3\x67", /* .entropylen = */ 48, /* .entpra = */ (unsigned char *) "\xe2\xbd\xb7\x48\x08\x06\xf3\xe1\x93\x3c\xac\x79" "\xa7\x2b\x11\xda\xe3\x2e\xe1\x91\xa5\x02\x19\x57" "\x20\x28\xad\xf2\x60\xd7\xcd\x45", /* .entprb = */ (unsigned char *) "\x8b\xd4\x69\xfc\xff\x59\x95\x95\xc6\x51\xde\x71" "\x68\x5f\xfc\xf9\x4a\xab\xec\x5a\xcb\xbe\xd3\x66" "\x1f\xfa\x74\xd3\xac\xa6\x74\x60", /* .entprlen = */ 32, /* .addtla = */ NULL, /* .addtlb = */ NULL, /* .addtllen = */ 0, /* .pers = */ (unsigned char *) "\x64\xb6\xfc\x60\xbc\x61\x76\x23\x6d\x3f\x4a\x0f" "\xe1\xb4\xd5\x20\x9e\x70\xdd\x03\x53\x6d\xbf\xce" "\xcd\x56\x80\xbc\xb8\x15\xc8\xaa", /* .perslen = */ 32, /* .expected = */ (unsigned char *) "\x1f\x9e\xaf\xe4\xd2\x46\xb7\x47\x41\x4c\x65\x99" "\x01\xe9\x3b\xbb\x83\x0c\x0a\xb0\xc1\x3a\xe2\xb3" "\x31\x4e\xeb\x93\x73\xee\x0b\x26\xc2\x63\xa5\x75" "\x45\x99\xd4\x5c\x9f\xa1\xd4\x45\x87\x6b\x20\x61" "\x40\xea\x78\xa5\x32\xdf\x9e\x66\x17\xaf\xb1\x88" "\x9e\x2e\x23\xdd\xc1\xda\x13\x97\x88\xa5\xb6\x5e" "\x90\x14\x4e\xef\x13\xab\x5c\xd9\x2c\x97\x9e\x7c" "\xd7\xf8\xce\xea\x81\xf5\xcd\x71\x15\x49\x44\xce" "\x83\xb6\x05\xfb\x7d\x30\xb5\x57\x2c\x31\x4f\xfc" "\xfe\x80\xb6\xc0\x13\x0c\x5b\x9b\x2e\x8f\x3d\xfc" "\xc2\xa3\x0c\x11\x1b\x80\x5f\xf3", /* .expectedlen = */ 128, /* .entropyreseed = */ NULL, /* .entropyreseed_len = */ 0, /* .addtl_reseed = */ NULL, /* .addtl_reseed_len = */ 0 }, { /* .flags = */ "aes sym128 pr", /* DRBG_PR_CTRAES128 */ /* .entropy = */ (unsigned char *) "\x92\x89\x8f\x31\xfa\x1c\xff\x6d\x18\x2f\x26\x06" "\x43\xdf\xf8\x18\xc2\xa4\xd9\x72\xc3\xb9\xb6\x97", /* .entropylen = */ 24, /* .entpra = */ (unsigned char *) "\x20\x72\x8a\x06\xf8\x6f\x8d\xd4\x41\xe2\x72\xb7" "\xc4\x2c\xe8\x10", /* .entprb = */ (unsigned char *) "\x3d\xb0\xf0\x94\xf3\x05\x50\x33\x17\x86\x3e\x22" "\x08\xf7\xa5\x01", /* .entprlen = */ 16, /* .addtla = */ (unsigned char *) "\x1a\x40\xfa\xe3\xcc\x6c\x7c\xa0\xf8\xda\xba\x59" "\x23\x6d\xad\x1d", /* .addtlb = */ (unsigned char *) "\x9f\x72\x76\x6c\xc7\x46\xe5\xed\x2e\x53\x20\x12" "\xbc\x59\x31\x8c", /* .addtllen = */ 16, /* .pers = */ (unsigned char *) "\xea\x65\xee\x60\x26\x4e\x7e\xb6\x0e\x82\x68\xc4" "\x37\x3c\x5c\x0b", /* .perslen = */ 16, /* .expected = */ (unsigned char *) "\x5a\x35\x39\x87\x0f\x4d\x22\xa4\x09\x24\xee\x71" "\xc9\x6f\xac\x72\x0a\xd6\xf0\x88\x82\xd0\x83\x28" "\x73\xec\x3f\x93\xd8\xab\x45\x23\xf0\x7e\xac\x45" "\x14\x5e\x93\x9f\xb1\xd6\x76\x43\x3d\xb6\xe8\x08" "\x88\xf6\xda\x89\x08\x77\x42\xfe\x1a\xf4\x3f\xc4" "\x23\xc5\x1f\x68", /* .expectedlen = */ 64, /* .entropyreseed = */ NULL, /* .entropyreseed_len = */ 0, /* .addtl_reseed = */ NULL, /* .addtl_reseed_len = */ 0 } }; struct gcry_drbg_test_vector drbg_test_nopr[] = { { /* .flags = */ "sha256" /* DRBG_NOPR_HASHSHA256 */, /* .entropy = */ (unsigned char *) "\x73\xd3\xfb\xa3\x94\x5f\x2b\x5f\xb9\x8f\xf6\x9c" "\x8a\x93\x17\xae\x19\xc3\x4c\xc3\xd6\xca\xa3\x2d" "\x16\xfc\x42\xd2\x2d\xd5\x6f\x56\xcc\x1d\x30\xff" "\x9e\x06\x3e\x09\xce\x58\xe6\x9a\x35\xb3\xa6\x56", /* .entropylen = */ 48, /* .entpra = */ NULL, /* .entprb = */ NULL, /* .entprlen = */ 0, /* .addtla = */ (unsigned char *) "\xf4\xd5\x98\x3d\xa8\xfc\xfa\x37\xb7\x54\x67\x73" "\xc7\xc3\xdd\x47\x34\x71\x02\x5d\xc1\xa0\xd3\x10" "\xc1\x8b\xbd\xf5\x66\x34\x6f\xdd", /* .addtlb = */ (unsigned char *) "\xf7\x9e\x6a\x56\x0e\x73\xe9\xd9\x7a\xd1\x69\xe0" "\x6f\x8c\x55\x1c\x44\xd1\xce\x6f\x28\xcc\xa4\x4d" "\xa8\xc0\x85\xd1\x5a\x0c\x59\x40", /* .addtllen = */ 32, /* .pers = */ NULL, /* .perslen = */ 0, /* .expected = */ (unsigned char *) "\x71\x7b\x93\x46\x1a\x40\xaa\x35\xa4\xaa\xc5\xe7" "\x6d\x5b\x5b\x8a\xa0\xdf\x39\x7d\xae\x71\x58\x5b" "\x3c\x7c\xb4\xf0\x89\xfa\x4a\x8c\xa9\x5c\x54\xc0" "\x40\xdf\xbc\xce\x26\x81\x34\xf8\xba\x7d\x1c\xe8" "\xad\x21\xe0\x74\xcf\x48\x84\x30\x1f\xa1\xd5\x4f" "\x81\x42\x2f\xf4\xdb\x0b\x23\xf8\x73\x27\xb8\x1d" "\x42\xf8\x44\x58\xd8\x5b\x29\x27\x0a\xf8\x69\x59" "\xb5\x78\x44\xeb\x9e\xe0\x68\x6f\x42\x9a\xb0\x5b" "\xe0\x4e\xcb\x6a\xaa\xe2\xd2\xd5\x33\x25\x3e\xe0" "\x6c\xc7\x6a\x07\xa5\x03\x83\x9f\xe2\x8b\xd1\x1c" "\x70\xa8\x07\x59\x97\xeb\xf6\xbe", /* .expectedlen = */ 128, /* .entropyreseed = */ NULL, /* .entropyreseed_len = */ 0, /* .addtl_reseed = */ NULL, /* .addtl_reseed_len = */ 0 }, { /* .flags = */ "hmac sha256" /* DRBG_NOPR_HMACSHA256 */, /* .entropy = */ (unsigned char *) "\x8d\xf0\x13\xb4\xd1\x03\x52\x30\x73\x91\x7d\xdf" "\x6a\x86\x97\x93\x05\x9e\x99\x43\xfc\x86\x54\x54" "\x9e\x7a\xb2\x2f\x7c\x29\xf1\x22\xda\x26\x25\xaf" "\x2d\xdd\x4a\xbc\xce\x3c\xf4\xfa\x46\x59\xd8\x4e", /* .entropylen = */ 48, /* .entpra = */ NULL, /* .entprb = */ NULL, /* .entprlen = */ 0, /* .addtla = */ NULL, /* .addtlb = */ NULL, /* .addtllen = */ 0, /* .pers = */ (unsigned char *) "\xb5\x71\xe6\x6d\x7c\x33\x8b\xc0\x7b\x76\xad\x37" "\x57\xbb\x2f\x94\x52\xbf\x7e\x07\x43\x7a\xe8\x58" "\x1c\xe7\xbc\x7c\x3a\xc6\x51\xa9", /* .perslen = */ 32, /* .expected = */ (unsigned char *) "\xb9\x1c\xba\x4c\xc8\x4f\xa2\x5d\xf8\x61\x0b\x81" "\xb6\x41\x40\x27\x68\xa2\x09\x72\x34\x93\x2e\x37" "\xd5\x90\xb1\x15\x4c\xbd\x23\xf9\x74\x52\xe3\x10" "\xe2\x91\xc4\x51\x46\x14\x7f\x0d\xa2\xd8\x17\x61" "\xfe\x90\xfb\xa6\x4f\x94\x41\x9c\x0f\x66\x2b\x28" "\xc1\xed\x94\xda\x48\x7b\xb7\xe7\x3e\xec\x79\x8f" "\xbc\xf9\x81\xb7\x91\xd1\xbe\x4f\x17\x7a\x89\x07" "\xaa\x3c\x40\x16\x43\xa5\xb6\x2b\x87\xb8\x9d\x66" "\xb3\xa6\x0e\x40\xd4\xa8\xe4\xe9\xd8\x2a\xf6\xd2" "\x70\x0e\x6f\x53\x5c\xdb\x51\xf7\x5c\x32\x17\x29" "\x10\x37\x41\x03\x0c\xcc\x3a\x56", /* .expectedlen = */ 128, /* .entropyreseed = */ NULL, /* .entropyreseed_len = */ 0, /* .addtl_reseed = */ NULL, /* .addtl_reseed_len = */ 0 }, { /* .flags = */ "aes sym128" /* DRBG_NOPR_CTRAES128 */, /* .entropy = */ (unsigned char *) "\xc0\x70\x1f\x92\x50\x75\x8f\xcd\xf2\xbe\x73\x98" "\x80\xdb\x66\xeb\x14\x68\xb4\xa5\x87\x9c\x2d\xa6", /* .entropylen = */ 24, /* .entpra = */ NULL, /* .entprb = */ NULL, /* .entprlen = */ 0, /* .addtla = */ (unsigned char *) "\xf9\x01\xf8\x16\x7a\x1d\xff\xde\x8e\x3c\x83\xe2" "\x44\x85\xe7\xfe", /* .addtlb = */ (unsigned char *) "\x17\x1c\x09\x38\xc2\x38\x9f\x97\x87\x60\x55\xb4" "\x82\x16\x62\x7f", /* .addtllen = */ 16, /* .pers = */ (unsigned char *) "\x80\x08\xae\xe8\xe9\x69\x40\xc5\x08\x73\xc7\x9f" "\x8e\xcf\xe0\x02", /* .perslen = */ 16, /* .expected = */ (unsigned char *) "\x97\xc0\xc0\xe5\xa0\xcc\xf2\x4f\x33\x63\x48\x8a" "\xdb\x13\x0a\x35\x89\xbf\x80\x65\x62\xee\x13\x95" "\x7c\x33\xd3\x7d\xf4\x07\x77\x7a\x2b\x65\x0b\x5f" "\x45\x5c\x13\xf1\x90\x77\x7f\xc5\x04\x3f\xcc\x1a" "\x38\xf8\xcd\x1b\xbb\xd5\x57\xd1\x4a\x4c\x2e\x8a" "\x2b\x49\x1e\x5c", /* .expectedlen = */ 64, /* .entropyreseed = */ NULL, /* .entropyreseed_len = */ 0, /* .addtl_reseed = */ NULL, /* .addtl_reseed_len = */ 0 }, { /* .flags = */ "sha1" /* DRBG_NOPR_HASHSHA1 */, /* .entropy = */ (unsigned char *) "\x16\x10\xb8\x28\xcc\xd2\x7d\xe0\x8c\xee\xa0\x32" "\xa2\x0e\x92\x08\x49\x2c\xf1\x70\x92\x42\xf6\xb5", /* .entropylen = */ 24, /* .entpra = */ NULL, /* .entprb = */ NULL, /* .entprlen = */ 0, /* .addtla = */ NULL, /* .addtlb = */ NULL, /* .addtllen = */ 0, /* .pers = */ NULL, /* .perslen = */ 0, /* .expected = */ (unsigned char *) "\x56\xf3\x3d\x4f\xdb\xb9\xa5\xb6\x4d\x26\x23\x44" "\x97\xe9\xdc\xb8\x77\x98\xc6\x8d\x08\xf7\xc4\x11" "\x99\xd4\xbd\xdf\x97\xeb\xbf\x6c\xb5\x55\x0e\x5d" "\x14\x9f\xf4\xd5\xbd\x0f\x05\xf2\x5a\x69\x88\xc1" "\x74\x36\x39\x62\x27\x18\x4a\xf8\x4a\x56\x43\x35" "\x65\x8e\x2f\x85\x72\xbe\xa3\x33\xee\xe2\xab\xff" "\x22\xff\xa6\xde\x3e\x22\xac\xa2", /* .expectedlen = */ 80, /* .entropyreseed = */ (unsigned char *) "\x72\xd2\x8c\x90\x8e\xda\xf9\xa4\xd1\xe5\x26\xd8" "\xf2\xde\xd5\x44", /* .entropyreseed_len = */ 16, /* .addtl_reseed = */ NULL, /* .addtl_reseed_len = */ 0 }, { /* .flags = */ "sha1" /* DRBG_NOPR_HASHSHA1 */, /* .entropy = */ (unsigned char *) "\xd9\xba\xb5\xce\xdc\xa9\x6f\x61\x78\xd6\x45\x09" "\xa0\xdf\xdc\x5e\xda\xd8\x98\x94\x14\x45\x0e\x01", /* .entropylen = */ 24, /* .entpra = */ NULL, /* .entprb = */ NULL, /* .entprlen = */ 0, /* .addtla = */ (unsigned char *) "\x04\xfa\x28\x95\xaa\x5a\x6f\x8c\x57\x43\x34\x3b" "\x80\x5e\x5e\xa4", /* .addtlb = */ (unsigned char *) "\xdf\x5d\xc4\x59\xdf\xf0\x2a\xa2\xf0\x52\xd7\x21" "\xec\x60\x72\x30", /* .addtllen = */ 16, /* .pers = */ NULL, /* .perslen = */ 0, /* .expected = */ (unsigned char *) "\xc4\x8b\x89\xf9\xda\x3f\x74\x82\x45\x55\x5d\x5d" "\x03\x3b\x69\x3d\xd7\x1a\x4d\xf5\x69\x02\x05\xce" "\xfc\xd7\x20\x11\x3c\xc2\x4e\x09\x89\x36\xff\x5e" "\x77\xb5\x41\x53\x58\x70\xb3\x39\x46\x8c\xdd\x8d" "\x6f\xaf\x8c\x56\x16\x3a\x70\x0a\x75\xb2\x3e\x59" "\x9b\x5a\xec\xf1\x6f\x3b\xaf\x6d\x5f\x24\x19\x97" "\x1f\x24\xf4\x46\x72\x0f\xea\xbe", /* .expectedlen = */ 80, /* .entropyreseed = */ (unsigned char *) "\xc6\xba\xd0\x74\xc5\x90\x67\x86\xf5\xe1\xf3\x20" "\x99\xf5\xb4\x91", /* .entropyreseed_len = */ 16, /* .addtl_reseed = */ (unsigned char *) "\x3e\x6b\xf4\x6f\x4d\xaa\x38\x25\xd7\x19\x4e\x69" "\x4e\x77\x52\xf7", /* .addtl_reseed_len = */ 16 } }; /* * Tests implement the CAVS test approach as documented in * http://csrc.nist.gov/groups/STM/cavp/documents/drbg/DRBGVS.pdf */ /* * CAVS test * * This function is not static as it is needed for as a private API * call for the CAVS test tool. */ gpg_err_code_t _gcry_rngdrbg_cavs_test (struct gcry_drbg_test_vector *test, unsigned char *buf) { gpg_err_code_t ret = 0; drbg_state_t drbg = NULL; struct drbg_test_data_s test_data; drbg_string_t addtl, pers, testentropy; int coreref = 0; int pr = 0; u32 flags; ret = parse_flag_string (test->flagstr, &flags); if (ret) goto outbuf; ret = drbg_algo_available (flags, &coreref); if (ret) goto outbuf; drbg = xtrycalloc_secure (1, sizeof *drbg); if (!drbg) { ret = gpg_err_code_from_syserror (); goto outbuf; } if ((flags & DRBG_PREDICTION_RESIST)) pr = 1; test_data.testentropy = &testentropy; drbg_string_fill (&testentropy, test->entropy, test->entropylen); drbg->test_data = &test_data; drbg_string_fill (&pers, test->pers, test->perslen); ret = drbg_instantiate (drbg, &pers, coreref, pr); if (ret) goto outbuf; if (test->entropyreseed) { drbg_string_fill (&testentropy, test->entropyreseed, test->entropyreseed_len); drbg_string_fill (&addtl, test->addtl_reseed, test->addtl_reseed_len); if (drbg_reseed (drbg, &addtl)) goto outbuf; } drbg_string_fill (&addtl, test->addtla, test->addtllen); if (test->entpra) { drbg_string_fill (&testentropy, test->entpra, test->entprlen); drbg->test_data = &test_data; } drbg_generate_long (drbg, buf, test->expectedlen, &addtl); drbg_string_fill (&addtl, test->addtlb, test->addtllen); if (test->entprb) { drbg_string_fill (&testentropy, test->entprb, test->entprlen); drbg->test_data = &test_data; } drbg_generate_long (drbg, buf, test->expectedlen, &addtl); drbg_uninstantiate (drbg); outbuf: xfree (drbg); return ret; } /* * Invoke the CAVS test and perform the final check whether the * calculated random value matches the expected one. * * This function is not static as it is needed for as a private API * call for the CAVS test tool. */ gpg_err_code_t _gcry_rngdrbg_healthcheck_one (struct gcry_drbg_test_vector * test) { gpg_err_code_t ret = GPG_ERR_ENOMEM; unsigned char *buf = xcalloc_secure (1, test->expectedlen); if (!buf) return GPG_ERR_ENOMEM; ret = _gcry_rngdrbg_cavs_test (test, buf); /* FIXME: The next line is wrong. */ ret = memcmp (test->expected, buf, test->expectedlen); xfree (buf); return ret; } /* * Tests as defined in 11.3.2 in addition to the cipher tests: testing * of the error handling. * * Note, testing the reseed counter is not done as an automatic reseeding * is performed in drbg_generate when the reseed counter is too large. */ static gpg_err_code_t drbg_healthcheck_sanity (struct gcry_drbg_test_vector *test) { unsigned int len = 0; drbg_state_t drbg = NULL; gpg_err_code_t ret = GPG_ERR_GENERAL; gpg_err_code_t tmpret = GPG_ERR_GENERAL; struct drbg_test_data_s test_data; drbg_string_t addtl, testentropy; int coreref = 0; unsigned char *buf = NULL; size_t max_addtllen, max_request_bytes; u32 flags; /* only perform test in FIPS mode */ if (0 == fips_mode ()) return 0; ret = parse_flag_string (test->flagstr, &flags); if (ret) return ret; ret = GPG_ERR_GENERAL; /* Fixme: Improve handling of RET. */ buf = xtrycalloc_secure (1, test->expectedlen); if (!buf) return gpg_err_code_from_syserror (); tmpret = drbg_algo_available (flags, &coreref); if (tmpret) goto outbuf; drbg = xtrycalloc_secure (1, sizeof *drbg); if (!drbg) { ret = gpg_err_code_from_syserror (); goto outbuf; } /* if the following tests fail, it is likely that there is a buffer * overflow and we get a SIGSEV */ ret = drbg_instantiate (drbg, NULL, coreref, 1); if (ret) goto outbuf; max_addtllen = drbg_max_addtl (); max_request_bytes = drbg_max_request_bytes (); - /* overflow addtllen with additonal info string */ + /* overflow addtllen with additional info string */ drbg_string_fill (&addtl, test->addtla, (max_addtllen + 1)); len = drbg_generate (drbg, buf, test->expectedlen, &addtl); if (len) goto outdrbg; /* overflow max_bits */ len = drbg_generate (drbg, buf, (max_request_bytes + 1), NULL); if (len) goto outdrbg; drbg_uninstantiate (drbg); /* test failing entropy source as defined in 11.3.2 */ test_data.testentropy = NULL; test_data.fail_seed_source = 1; drbg->test_data = &test_data; tmpret = drbg_instantiate (drbg, NULL, coreref, 0); if (!tmpret) goto outdrbg; test_data.fail_seed_source = 0; test_data.testentropy = &testentropy; drbg_string_fill (&testentropy, test->entropy, test->entropylen); /* overflow max addtllen with personalization string */ tmpret = drbg_instantiate (drbg, &addtl, coreref, 0); if (!tmpret) goto outdrbg; dbg (("DRBG: Sanity tests for failure code paths successfully completed\n")); ret = 0; outdrbg: drbg_uninstantiate (drbg); outbuf: xfree (buf); xfree (drbg); return ret; } /* * DRBG Healthcheck function as required in SP800-90A * * return: * 0 on success (all tests pass) * >0 on error (return code indicate the number of failures) */ static int drbg_healthcheck (void) { int ret = 0; ret += _gcry_rngdrbg_healthcheck_one (&drbg_test_nopr[0]); ret += _gcry_rngdrbg_healthcheck_one (&drbg_test_nopr[1]); ret += _gcry_rngdrbg_healthcheck_one (&drbg_test_nopr[2]); ret += _gcry_rngdrbg_healthcheck_one (&drbg_test_nopr[3]); ret += _gcry_rngdrbg_healthcheck_one (&drbg_test_nopr[4]); ret += _gcry_rngdrbg_healthcheck_one (&drbg_test_pr[0]); ret += _gcry_rngdrbg_healthcheck_one (&drbg_test_pr[1]); ret += _gcry_rngdrbg_healthcheck_one (&drbg_test_pr[2]); ret += drbg_healthcheck_sanity (&drbg_test_nopr[0]); return ret; } /* Run the self-tests. */ gcry_error_t _gcry_rngdrbg_selftest (selftest_report_func_t report) { gcry_err_code_t ec; const char *errtxt = NULL; drbg_lock (); if (0 != drbg_healthcheck ()) errtxt = "RNG output does not match known value"; drbg_unlock (); if (report && errtxt) report ("random", 0, "KAT", errtxt); ec = errtxt ? GPG_ERR_SELFTEST_FAILED : 0; return gpg_error (ec); } /*************************************************************** * Cipher invocations requested by DRBG ***************************************************************/ static gpg_err_code_t drbg_hash_init (drbg_state_t drbg) { gcry_md_hd_t hd; gpg_error_t err; err = _gcry_md_open (&hd, drbg->core->backend_cipher, 0); if (err) return err; drbg->priv_data = hd; return 0; } static gpg_err_code_t drbg_hmac_init (drbg_state_t drbg) { gcry_md_hd_t hd; gpg_error_t err; err = _gcry_md_open (&hd, drbg->core->backend_cipher, GCRY_MD_FLAG_HMAC); if (err) return err; drbg->priv_data = hd; return 0; } static gpg_err_code_t drbg_hmac_setkey (drbg_state_t drbg, const unsigned char *key) { gcry_md_hd_t hd = (gcry_md_hd_t)drbg->priv_data; return _gcry_md_setkey (hd, key, drbg_statelen (drbg)); } static void drbg_hash_fini (drbg_state_t drbg) { gcry_md_hd_t hd = (gcry_md_hd_t)drbg->priv_data; _gcry_md_close (hd); } static byte * drbg_hash (drbg_state_t drbg, const drbg_string_t *buf) { gcry_md_hd_t hd = (gcry_md_hd_t)drbg->priv_data; _gcry_md_reset(hd); for (; NULL != buf; buf = buf->next) _gcry_md_write (hd, buf->buf, buf->len); _gcry_md_final (hd); return _gcry_md_read (hd, drbg->core->backend_cipher); } static void drbg_sym_fini (drbg_state_t drbg) { gcry_cipher_hd_t hd = (gcry_cipher_hd_t)drbg->priv_data; if (hd) _gcry_cipher_close (hd); if (drbg->ctr_handle) _gcry_cipher_close (drbg->ctr_handle); if (drbg->ctr_null) free(drbg->ctr_null); } static gpg_err_code_t drbg_sym_init (drbg_state_t drbg) { gcry_cipher_hd_t hd; gpg_error_t err; drbg->ctr_null = calloc(1, DRBG_CTR_NULL_LEN); if (!drbg->ctr_null) return GPG_ERR_ENOMEM; err = _gcry_cipher_open (&hd, drbg->core->backend_cipher, GCRY_CIPHER_MODE_ECB, 0); if (err) { drbg_sym_fini (drbg); return err; } drbg->priv_data = hd; err = _gcry_cipher_open (&drbg->ctr_handle, drbg->core->backend_cipher, GCRY_CIPHER_MODE_CTR, 0); if (err) { drbg_sym_fini (drbg); return err; } if (drbg_blocklen (drbg) != _gcry_cipher_get_algo_blklen (drbg->core->backend_cipher)) { drbg_sym_fini (drbg); return -GPG_ERR_NO_ERROR; } return 0; } static gpg_err_code_t drbg_sym_setkey (drbg_state_t drbg, const unsigned char *key) { gcry_cipher_hd_t hd = (gcry_cipher_hd_t)drbg->priv_data; return _gcry_cipher_setkey (hd, key, drbg_keylen (drbg)); } static gpg_err_code_t drbg_sym (drbg_state_t drbg, unsigned char *outval, const drbg_string_t *buf) { gcry_cipher_hd_t hd = (gcry_cipher_hd_t)drbg->priv_data; _gcry_cipher_reset(hd); if (drbg_blocklen (drbg) < buf->len) return -GPG_ERR_NO_ERROR; /* in is only component */ return _gcry_cipher_encrypt (hd, outval, drbg_blocklen (drbg), buf->buf, buf->len); } static gpg_err_code_t drbg_sym_ctr (drbg_state_t drbg, const unsigned char *inbuf, unsigned int inbuflen, unsigned char *outbuf, unsigned int outbuflen) { gpg_error_t err; _gcry_cipher_reset(drbg->ctr_handle); err = _gcry_cipher_setctr(drbg->ctr_handle, drbg->V, drbg_blocklen (drbg)); if (err) return err; while (outbuflen) { unsigned int cryptlen = (inbuflen > outbuflen) ? outbuflen : inbuflen; err = _gcry_cipher_encrypt (drbg->ctr_handle, outbuf, cryptlen, inbuf, cryptlen); if (err) return err; outbuflen -= cryptlen; outbuf += cryptlen; } return _gcry_cipher_getctr(drbg->ctr_handle, drbg->V, drbg_blocklen (drbg)); } diff --git a/random/rndhw.c b/random/rndhw.c index e3a78615..2829382c 100644 --- a/random/rndhw.c +++ b/random/rndhw.c @@ -1,221 +1,221 @@ /* rndhw.c - Access to the external random daemon * Copyright (C) 2007 Free Software Foundation, Inc. * Copyright (C) 2012 Dmitry Kasatkin * * 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 . */ #include #include #include #include "types.h" #include "g10lib.h" #include "rand-internal.h" #undef USE_PADLOCK #ifdef ENABLE_PADLOCK_SUPPORT # ifdef HAVE_GCC_ATTRIBUTE_ALIGNED # if (defined (__i386__) && SIZEOF_UNSIGNED_LONG == 4) || defined(__x86_64__) # define USE_PADLOCK 1 # endif # endif #endif /*ENABLE_PADLOCK_SUPPORT*/ #undef USE_DRNG #ifdef ENABLE_DRNG_SUPPORT # ifdef HAVE_GCC_ATTRIBUTE_ALIGNED # if (defined (__i386__) && SIZEOF_UNSIGNED_LONG == 4) || defined(__x86_64__) # define USE_DRNG 1 # endif # endif #endif /*ENABLE_RDRAND_SUPPORT*/ typedef void (*add_fn_t)(const void*, size_t, enum random_origins); /* Keep track on whether the RNG has problems. */ static volatile int rng_failed; #ifdef USE_PADLOCK static size_t poll_padlock (void (*add)(const void*, size_t, enum random_origins), enum random_origins origin, int fast) { volatile char buffer[64+8] __attribute__ ((aligned (8))); volatile char *p; unsigned int nbytes, status; /* Peter Gutmann's cryptlib tests again whether the RNG is enabled but we don't do so. We would have to do this also for our AES - implementaion and that is definitely too time consuming. There + implementation and that is definitely too time consuming. There would be a race condition anyway. Thus we assume that the OS does not change the Padlock initialization while a user process is running. */ p = buffer; nbytes = 0; while (nbytes < 64) { #if defined(__x86_64__) && SIZEOF_VOID_P == 8 asm volatile ("movq %1, %%rdi\n\t" /* Set buffer. */ "xorq %%rdx, %%rdx\n\t" /* Request up to 8 bytes. */ ".byte 0x0f, 0xa7, 0xc0\n\t" /* XSTORE RNG. */ : "=a" (status) : "g" (p) : "%rdx", "%rdi", "cc", "memory" ); #else asm volatile ("movl %1, %%edi\n\t" /* Set buffer. */ "xorl %%edx, %%edx\n\t" /* Request up to 8 bytes. */ ".byte 0x0f, 0xa7, 0xc0\n\t" /* XSTORE RNG. */ : "=a" (status) : "g" (p) : "%edx", "%edi", "cc", "memory" ); #endif if ((status & (1<<6)) /* RNG still enabled. */ && !(status & (1<<13)) /* von Neumann corrector is enabled. */ && !(status & (1<<14)) /* String filter is disabled. */ && !(status & 0x1c00) /* BIAS voltage at default. */ && (!(status & 0x1f) || (status & 0x1f) == 8) /* Sanity check. */ ) { nbytes += (status & 0x1f); if (fast) break; /* Don't get into the loop with the fast flag set. */ p += (status & 0x1f); } else { /* If there was an error we need to break the loop and record that there is something wrong with the padlock RNG. */ rng_failed = 1; break; } } if (nbytes) { (*add) ((void*)buffer, nbytes, origin); wipememory (buffer, nbytes); } return nbytes; } #endif /*USE_PADLOCK*/ #ifdef USE_DRNG # define RDRAND_RETRY_LOOPS 10 # define RDRAND_INT ".byte 0x0f,0xc7,0xf0" # if defined(__x86_64__) && SIZEOF_UNSIGNED_LONG == 8 # define RDRAND_LONG ".byte 0x48,0x0f,0xc7,0xf0" # else # define RDRAND_LONG RDRAND_INT # endif static inline int rdrand_long (volatile unsigned long *v) { int ok; asm volatile ("1: " RDRAND_LONG "\n\t" "jc 2f\n\t" "decl %0\n\t" "jnz 1b\n\t" "2:" : "=r" (ok), "=a" (*v) : "0" (RDRAND_RETRY_LOOPS) : "cc", "memory"); return ok; } static inline int rdrand_nlong (volatile unsigned long *v, int count) { while (count--) if (!rdrand_long(v++)) return 0; return 1; } static size_t poll_drng (add_fn_t add, enum random_origins origin, int fast) { volatile unsigned long buffer[8] __attribute__ ((aligned (8))); unsigned int nbytes = sizeof (buffer); (void)fast; if (!rdrand_nlong (buffer, DIM(buffer))) return 0; (*add)((void *)buffer, nbytes, origin); return nbytes; } #endif /*USE_DRNG*/ int _gcry_rndhw_failed_p (void) { return rng_failed; } /* Try to read random from a hardware RNG if a fast one is available. */ void _gcry_rndhw_poll_fast (void (*add)(const void*, size_t, enum random_origins), enum random_origins origin) { (void)add; (void)origin; #ifdef USE_DRNG if ((_gcry_get_hw_features () & HWF_INTEL_RDRAND)) poll_drng (add, origin, 1); #endif #ifdef USE_PADLOCK if ((_gcry_get_hw_features () & HWF_PADLOCK_RNG)) poll_padlock (add, origin, 1); #endif } /* Read 64 bytes from a hardware RNG and return the number of bytes actually read. */ size_t _gcry_rndhw_poll_slow (void (*add)(const void*, size_t, enum random_origins), enum random_origins origin) { size_t nbytes = 0; (void)add; (void)origin; #ifdef USE_DRNG if ((_gcry_get_hw_features () & HWF_INTEL_RDRAND)) nbytes += poll_drng (add, origin, 0); #endif #ifdef USE_PADLOCK if ((_gcry_get_hw_features () & HWF_PADLOCK_RNG)) nbytes += poll_padlock (add, origin, 0); #endif return nbytes; } diff --git a/random/rndunix.c b/random/rndunix.c index e7238f49..fcb45b78 100644 --- a/random/rndunix.c +++ b/random/rndunix.c @@ -1,937 +1,937 @@ /**************************************************************************** * * * * * Unix Randomness-Gathering Code * * * * Copyright Peter Gutmann, Paul Kendall, and Chris Wedgwood 1996-1999. * * Heavily modified for GnuPG by Werner Koch * * * * * ****************************************************************************/ /* This module is part of the cryptlib continuously seeded pseudorandom number generator. For usage conditions, see lib_rand.c [Here is the notice from lib_rand.c:] This module and the misc/rnd*.c modules represent the cryptlib continuously seeded pseudorandom number generator (CSPRNG) as described in my 1998 Usenix Security Symposium paper "The generation of random numbers for cryptographic purposes". The CSPRNG code is copyright Peter Gutmann (and various others) 1996, 1997, 1998, 1999, all rights reserved. Redistribution of the CSPRNG modules and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice and this permission notice in its entirety. 2. Redistributions in binary form must reproduce the copyright notice in the documentation and/or other materials provided with the distribution. 3. A copy of any bugfixes or enhancements made must be provided to the author, to allow them to be added to the baseline version of the code. ALTERNATIVELY, the code may be distributed under the terms of the GNU Lesser General Public License, version 2.1 or any later version published by the Free Software Foundation, in which case the provisions of the GNU LGPL are required INSTEAD OF the above restrictions. Although not required under the terms of the LGPL, it would still be nice if you could make any changes available to the author to allow a consistent code base to be maintained. */ /************************************************************************* The above alternative was changed from GPL to LGPL on 2007-08-22 with permission from Peter Gutmann: ========== From: pgut001 Subject: Re: LGPL for the windows entropy gatherer To: wk@gnupg.org Date: Wed, 22 Aug 2007 03:05:42 +1200 Hi, >As of now libgcrypt is GPL under Windows due to that module and some people >would really like to see it under LGPL too. Can you do such a license change >to LGPL version 2? Note that LGPL give the user the option to relicense it >under GPL, so the change would be pretty easy and backwar compatible. Sure. I assumed that since GPG was GPLd, you'd prefer the GPL for the entropy code as well, but Ian asked for LGPL as an option so as of the next release I'll have LGPL in there. You can consider it to be retroactive, so your current version will be LGPLd as well. Peter. ========== From: pgut001 Subject: Re: LGPL for the windows entropy gatherer To: wk@gnupg.org Date: Wed, 22 Aug 2007 20:50:08 +1200 >Would you mind to extend this also to the Unix entropy gatherer which is >still used on systems without /dev/random and when EGD is not installed? That >would be the last GPLed piece in Libgcrypt. Sure, it covers the entire entropy-gathering subsystem. Peter. ========= */ /* General includes */ #include #include #include #ifdef HAVE_STDINT_H # include #endif #include /* OS-specific includes */ #ifdef __osf__ /* Somewhere in the morass of system-specific cruft which OSF/1 pulls in * via the following includes are various endianness defines, so we * undefine the cryptlib ones, which aren't really needed for this module * anyway */ #undef BIG_ENDIAN #undef LITTLE_ENDIAN #endif /* __osf__ */ #include #include #include #ifndef __QNX__ #include #include #endif /* __QNX__ */ #include /* SCO and SunOS need this before resource.h */ #ifndef __QNX__ #include #endif /* __QNX__ */ #if defined( _AIX ) || defined( __QNX__ ) #include #endif /* _AIX */ #ifndef __QNX__ #include #include #include #endif /* __QNX__ */ #include #include /* Verschiedene komische Typen */ #if defined( __hpux ) && ( OS_VERSION == 9 ) #include #endif /* __hpux 9.x, after that it's in unistd.h */ #include /* #include */ #ifdef __QNX__ #include #include #endif /* __QNX__ */ #include #include "types.h" /* for byte and u32 typedefs */ #include "g10lib.h" #include "rand-internal.h" #ifndef EAGAIN #define EAGAIN EWOULDBLOCK #endif #ifndef STDIN_FILENO #define STDIN_FILENO 0 #endif #ifndef STDOUT_FILENO #define STDOUT_FILENO 1 #endif #ifndef STDERR_FILENO #define STDERR_FILENO 2 #endif #define GATHER_BUFSIZE 49152 /* Usually about 25K are filled */ /* The structure containing information on random-data sources. Each * record contains the source and a relative estimate of its usefulness * (weighting) which is used to scale the number of kB of output from the * source (total = data_bytes / usefulness). Usually the weighting is in the * range 1-3 (or 0 for especially useless sources), resulting in a usefulness * rating of 1...3 for each kB of source output (or 0 for the useless * sources). * * If the source is constantly changing (certain types of network statistics * have this characteristic) but the amount of output is small, the weighting * is given as a negative value to indicate that the output should be treated * as if a minimum of 1K of output had been obtained. If the source produces * a lot of output then the scale factor is fractional, resulting in a * usefulness rating of < 1 for each kB of source output. * * In order to provide enough randomness to satisfy the requirements for a * slow poll, we need to accumulate at least 20 points of usefulness (a * typical system should get about 30 points). * * Some potential options are missed out because of special considerations. * pstat -i and pstat -f can produce amazing amounts of output (the record * is 600K on an Oracle server) which floods the buffer and doesn't yield * anything useful (apart from perhaps increasing the entropy of the vmstat * output a bit), so we don't bother with this. pstat in general produces * quite a bit of output, but it doesn't change much over time, so it gets * very low weightings. netstat -s produces constantly-changing output but * also produces quite a bit of it, so it only gets a weighting of 2 rather * than 3. The same holds for netstat -in, which gets 1 rather than 2. * * Some binaries are stored in different locations on different systems so * alternative paths are given for them. The code sorts out which one to * run by itself, once it finds an exectable somewhere it moves on to the * next source. The sources are arranged roughly in their order of * usefulness, occasionally sources which provide a tiny amount of * relatively useless data are placed ahead of ones which provide a large * amount of possibly useful data because another 100 bytes can't hurt, and * it means the buffer won't be swamped by one or two high-output sources. * All the high-output sources are clustered towards the end of the list * for this reason. Some binaries are checked for in a certain order, for * example under Slowaris /usr/ucb/ps understands aux as an arg, but the * others don't. Some systems have conditional defines enabling alternatives * to commands which don't understand the usual options but will provide * enough output (in the form of error messages) to look like they're the * real thing, causing alternative options to be skipped (we can't check the * return either because some commands return peculiar, non-zero status even * when they're working correctly). * * In order to maximise use of the buffer, the code performs a form of run- * length compression on its input where a repeated sequence of bytes is * replaced by the occurrence count mod 256. Some commands output an awful * lot of whitespace, this measure greatly increases the amount of data we * can fit in the buffer. * * When we scale the weighting using the SC() macro, some preprocessors may * give a division by zero warning for the most obvious expression * 'weight ? 1024 / weight : 0' (and gcc 2.7.2.2 dies with a division by zero * trap), so we define a value SC_0 which evaluates to zero when fed to * '1024 / SC_0' */ #define SC( weight ) ( 1024 / weight ) /* Scale factor */ #define SC_0 16384 /* SC( SC_0 ) evaluates to 0 */ static struct RI { const char *path; /* Path to check for existence of source */ const char *arg; /* Args for source */ const int usefulness; /* Usefulness of source */ FILE *pipe; /* Pipe to source as FILE * */ int pipeFD; /* Pipe to source as FD */ pid_t pid; /* pid of child for waitpid() */ int length; /* Quantity of output produced */ const int hasAlternative; /* Whether source has alt.location */ } dataSources[] = { { "/bin/vmstat", "-s", SC(-3), NULL, 0, 0, 0, 1 }, { "/usr/bin/vmstat", "-s", SC(-3), NULL, 0, 0, 0, 0}, { "/bin/vmstat", "-c", SC(-3), NULL, 0, 0, 0, 1 }, { "/usr/bin/vmstat", "-c", SC(-3), NULL, 0, 0, 0, 0}, { "/usr/bin/pfstat", NULL, SC(-2), NULL, 0, 0, 0, 0}, { "/bin/vmstat", "-i", SC(-2), NULL, 0, 0, 0, 1 }, { "/usr/bin/vmstat", "-i", SC(-2), NULL, 0, 0, 0, 0}, { "/usr/ucb/netstat", "-s", SC(2), NULL, 0, 0, 0, 1 }, { "/usr/bin/netstat", "-s", SC(2), NULL, 0, 0, 0, 1 }, { "/usr/sbin/netstat", "-s", SC(2), NULL, 0, 0, 0, 1}, { "/usr/etc/netstat", "-s", SC(2), NULL, 0, 0, 0, 0}, { "/usr/bin/nfsstat", NULL, SC(2), NULL, 0, 0, 0, 0}, { "/usr/ucb/netstat", "-m", SC(-1), NULL, 0, 0, 0, 1 }, { "/usr/bin/netstat", "-m", SC(-1), NULL, 0, 0, 0, 1 }, { "/usr/sbin/netstat", "-m", SC(-1), NULL, 0, 0, 0, 1 }, { "/usr/etc/netstat", "-m", SC(-1), NULL, 0, 0, 0, 0 }, { "/bin/netstat", "-in", SC(-1), NULL, 0, 0, 0, 1 }, { "/usr/ucb/netstat", "-in", SC(-1), NULL, 0, 0, 0, 1 }, { "/usr/bin/netstat", "-in", SC(-1), NULL, 0, 0, 0, 1 }, { "/usr/sbin/netstat", "-in", SC(-1), NULL, 0, 0, 0, 1}, { "/usr/etc/netstat", "-in", SC(-1), NULL, 0, 0, 0, 0}, { "/usr/sbin/snmp_request", "localhost public get 1.3.6.1.2.1.7.1.0", SC(-1), NULL, 0, 0, 0, 0 }, /* UDP in */ { "/usr/sbin/snmp_request", "localhost public get 1.3.6.1.2.1.7.4.0", SC(-1), NULL, 0, 0, 0, 0 }, /* UDP out */ { "/usr/sbin/snmp_request", "localhost public get 1.3.6.1.2.1.4.3.0", SC(-1), NULL, 0, 0, 0, 0 }, /* IP ? */ { "/usr/sbin/snmp_request", "localhost public get 1.3.6.1.2.1.6.10.0", SC(-1), NULL, 0, 0, 0, 0 }, /* TCP ? */ { "/usr/sbin/snmp_request", "localhost public get 1.3.6.1.2.1.6.11.0", SC(-1), NULL, 0, 0, 0, 0 }, /* TCP ? */ { "/usr/sbin/snmp_request", "localhost public get 1.3.6.1.2.1.6.13.0", SC(-1), NULL, 0, 0, 0, 0 }, /* TCP ? */ { "/usr/bin/mpstat", NULL, SC(1), NULL, 0, 0, 0, 0 }, { "/usr/bin/w", NULL, SC(1), NULL, 0, 0, 0, 1 }, { "/usr/bsd/w", NULL, SC(1), NULL, 0, 0, 0, 0 }, { "/usr/bin/df", NULL, SC(1), NULL, 0, 0, 0, 1 }, { "/bin/df", NULL, SC(1), NULL, 0, 0, 0, 0 }, { "/usr/sbin/portstat", NULL, SC(1), NULL, 0, 0, 0, 0 }, { "/usr/bin/iostat", NULL, SC(SC_0), NULL, 0, 0, 0, 0 }, { "/usr/bin/uptime", NULL, SC(SC_0), NULL, 0, 0, 0, 1 }, { "/usr/bsd/uptime", NULL, SC(SC_0), NULL, 0, 0, 0, 0 }, { "/bin/vmstat", "-f", SC(SC_0), NULL, 0, 0, 0, 1 }, { "/usr/bin/vmstat", "-f", SC(SC_0), NULL, 0, 0, 0, 0 }, { "/bin/vmstat", NULL, SC(SC_0), NULL, 0, 0, 0, 1 }, { "/usr/bin/vmstat", NULL, SC(SC_0), NULL, 0, 0, 0, 0 }, { "/usr/ucb/netstat", "-n", SC(0.5), NULL, 0, 0, 0, 1 }, { "/usr/bin/netstat", "-n", SC(0.5), NULL, 0, 0, 0, 1 }, { "/usr/sbin/netstat", "-n", SC(0.5), NULL, 0, 0, 0, 1 }, { "/usr/etc/netstat", "-n", SC(0.5), NULL, 0, 0, 0, 0 }, #if defined( __sgi ) || defined( __hpux ) { "/bin/ps", "-el", SC(0.3), NULL, 0, 0, 0, 1 }, #endif /* __sgi || __hpux */ { "/usr/ucb/ps", "aux", SC(0.3), NULL, 0, 0, 0, 1 }, { "/usr/bin/ps", "aux", SC(0.3), NULL, 0, 0, 0, 1 }, { "/bin/ps", "aux", SC(0.3), NULL, 0, 0, 0, 0 }, { "/bin/ps", "-A", SC(0.3), NULL, 0, 0, 0, 0 }, /*QNX*/ { "/usr/bin/ipcs", "-a", SC(0.5), NULL, 0, 0, 0, 1 }, { "/bin/ipcs", "-a", SC(0.5), NULL, 0, 0, 0, 0 }, /* Unreliable source, depends on system usage */ { "/etc/pstat", "-p", SC(0.5), NULL, 0, 0, 0, 1 }, { "/bin/pstat", "-p", SC(0.5), NULL, 0, 0, 0, 0 }, { "/etc/pstat", "-S", SC(0.2), NULL, 0, 0, 0, 1 }, { "/bin/pstat", "-S", SC(0.2), NULL, 0, 0, 0, 0 }, { "/etc/pstat", "-v", SC(0.2), NULL, 0, 0, 0, 1 }, { "/bin/pstat", "-v", SC(0.2), NULL, 0, 0, 0, 0 }, { "/etc/pstat", "-x", SC(0.2), NULL, 0, 0, 0, 1 }, { "/bin/pstat", "-x", SC(0.2), NULL, 0, 0, 0, 0 }, { "/etc/pstat", "-t", SC(0.1), NULL, 0, 0, 0, 1 }, { "/bin/pstat", "-t", SC(0.1), NULL, 0, 0, 0, 0 }, /* pstat is your friend */ { "/usr/bin/last", "-n 50", SC(0.3), NULL, 0, 0, 0, 1 }, #ifdef __sgi { "/usr/bsd/last", "-50", SC(0.3), NULL, 0, 0, 0, 0 }, #endif /* __sgi */ #ifdef __hpux { "/etc/last", "-50", SC(0.3), NULL, 0, 0, 0, 0 }, #endif /* __hpux */ { "/usr/bsd/last", "-n 50", SC(0.3), NULL, 0, 0, 0, 0 }, { "/usr/sbin/snmp_request", "localhost public get 1.3.6.1.2.1.5.1.0", SC(0.1), NULL, 0, 0, 0, 0 }, /* ICMP ? */ { "/usr/sbin/snmp_request", "localhost public get 1.3.6.1.2.1.5.3.0", SC(0.1), NULL, 0, 0, 0, 0 }, /* ICMP ? */ { "/etc/arp", "-a", SC(0.1), NULL, 0, 0, 0, 1 }, { "/usr/etc/arp", "-a", SC(0.1), NULL, 0, 0, 0, 1 }, { "/usr/bin/arp", "-a", SC(0.1), NULL, 0, 0, 0, 1 }, { "/usr/sbin/arp", "-a", SC(0.1), NULL, 0, 0, 0, 0 }, { "/usr/sbin/ripquery", "-nw 1 127.0.0.1", SC(0.1), NULL, 0, 0, 0, 0 }, { "/bin/lpstat", "-t", SC(0.1), NULL, 0, 0, 0, 1 }, { "/usr/bin/lpstat", "-t", SC(0.1), NULL, 0, 0, 0, 1 }, { "/usr/ucb/lpstat", "-t", SC(0.1), NULL, 0, 0, 0, 0 }, { "/usr/bin/tcpdump", "-c 5 -efvvx", SC(1), NULL, 0, 0, 0, 0 }, - /* This is very environment-dependant. If network traffic is low, it'll + /* This is very environment-dependent. If network traffic is low, it'll * probably time out before delivering 5 packets, which is OK because * it'll probably be fixed stuff like ARP anyway */ { "/usr/sbin/advfsstat", "-b usr_domain", SC(SC_0), NULL, 0, 0, 0, 0}, { "/usr/sbin/advfsstat", "-l 2 usr_domain", SC(0.5), NULL, 0, 0, 0, 0}, { "/usr/sbin/advfsstat", "-p usr_domain", SC(SC_0), NULL, 0, 0, 0, 0}, /* This is a complex and screwball program. Some systems have things * like rX_dmn, x = integer, for RAID systems, but the statistics are * pretty dodgy */ #ifdef __QNXNTO__ { "/bin/pidin", "-F%A%B%c%d%E%I%J%K%m%M%n%N%p%P%S%s%T", SC(0.3), NULL, 0, 0, 0, 0 }, #endif #if 0 /* The following aren't enabled since they're somewhat slow and not very * unpredictable, however they give an indication of the sort of sources * you can use (for example the finger might be more useful on a * firewalled internal network) */ { "/usr/bin/finger", "@ml.media.mit.edu", SC(0.9), NULL, 0, 0, 0, 0 }, { "/usr/local/bin/wget", "-O - http://lavarand.sgi.com/block.html", SC(0.9), NULL, 0, 0, 0, 0 }, { "/bin/cat", "/usr/spool/mqueue/syslog", SC(0.9), NULL, 0, 0, 0, 0 }, #endif /* 0 */ { NULL, NULL, 0, NULL, 0, 0, 0, 0 } }; static byte *gather_buffer; /* buffer for gathering random noise */ static int gather_buffer_size; /* size of the memory buffer */ static uid_t gatherer_uid; /* The message structure used to communicate with the parent */ typedef struct { int usefulness; /* usefulness of data */ int ndata; /* valid bytes in data */ char data[500]; /* gathered data */ } GATHER_MSG; #ifndef HAVE_WAITPID static pid_t waitpid(pid_t pid, int *statptr, int options) { #ifdef HAVE_WAIT4 return wait4(pid, statptr, options, NULL); #else /* If wait4 is also not available, try wait3 for SVR3 variants */ /* Less ideal because can't actually request a specific pid */ /* For that reason, first check to see if pid is for an */ /* existing process. */ int tmp_pid, dummystat;; if (kill(pid, 0) == -1) { errno = ECHILD; return -1; } if (statptr == NULL) statptr = &dummystat; while (((tmp_pid = wait3(statptr, options, 0)) != pid) && (tmp_pid != -1) && (tmp_pid != 0) && (pid != -1)) ; return tmp_pid; #endif } #endif /* Under SunOS popen() doesn't record the pid of the child process. When * pclose() is called, instead of calling waitpid() for the correct child, it * calls wait() repeatedly until the right child is reaped. The problem is * that this reaps any other children that happen to have died at that * moment, and when their pclose() comes along, the process hangs forever. * The fix is to use a wrapper for popen()/pclose() which saves the pid in * the dataSources structure (code adapted from GNU-libc's popen() call). * * Aut viam inveniam aut faciam */ static FILE * my_popen(struct RI *entry) { int pipedes[2]; FILE *stream; /* Create the pipe */ if (pipe(pipedes) < 0) return (NULL); /* Fork off the child ("vfork() is like an OS orgasm. All OS's want to * do it, but most just end up faking it" - Chris Wedgwood). If your OS * supports it, you should try to use vfork() here because it's somewhat * more efficient */ #if defined( sun ) || defined( __ultrix__ ) || defined( __osf__ ) || \ defined(__hpux) entry->pid = vfork(); #else /* */ entry->pid = fork(); #endif /* Unixen which have vfork() */ if (entry->pid == (pid_t) - 1) { /* The fork failed */ close(pipedes[0]); close(pipedes[1]); return (NULL); } if (entry->pid == (pid_t) 0) { struct passwd *passwd; /* We are the child. Make the read side of the pipe be stdout */ if (dup2(pipedes[STDOUT_FILENO], STDOUT_FILENO) < 0) exit(127); /* Now that everything is set up, give up our permissions to make * sure we don't read anything sensitive. If the getpwnam() fails, * we default to -1, which is usually nobody */ if (gatherer_uid == (uid_t)-1 && \ (passwd = getpwnam("nobody")) != NULL) gatherer_uid = passwd->pw_uid; setuid(gatherer_uid); /* Close the pipe descriptors */ close(pipedes[STDIN_FILENO]); close(pipedes[STDOUT_FILENO]); /* Try and exec the program */ execl(entry->path, entry->path, entry->arg, NULL); /* Die if the exec failed */ exit(127); } /* We are the parent. Close the irrelevant side of the pipe and open * the relevant side as a new stream. Mark our side of the pipe to * close on exec, so new children won't see it */ close(pipedes[STDOUT_FILENO]); #ifdef FD_CLOEXEC fcntl(pipedes[STDIN_FILENO], F_SETFD, FD_CLOEXEC); #endif stream = fdopen(pipedes[STDIN_FILENO], "r"); if (stream == NULL) { int savedErrno = errno; /* The stream couldn't be opened or the child structure couldn't be * allocated. Kill the child and close the other side of the pipe */ kill(entry->pid, SIGKILL); if (stream == NULL) close(pipedes[STDOUT_FILENO]); else fclose(stream); waitpid(entry->pid, NULL, 0); entry->pid = 0; errno = savedErrno; return (NULL); } return (stream); } static int my_pclose(struct RI *entry) { int status = 0; if (fclose(entry->pipe)) return (-1); /* We ignore the return value from the process because some programs return funny values which would result in the input being discarded even if they executed successfully. This isn't a problem because the result data size threshold will filter out any programs which exit with a usage message without producing useful output. */ if (waitpid(entry->pid, NULL, 0) != entry->pid) status = -1; entry->pipe = NULL; entry->pid = 0; return (status); } /* Unix slow poll (without special support for Linux) * * If a few of the randomness sources create a large amount of output then * the slowPoll() stops once the buffer has been filled (but before all the * randomness sources have been sucked dry) so that the 'usefulness' factor * remains below the threshold. For this reason the gatherer buffer has to * be fairly sizeable on moderately loaded systems. This is something of a * bug since the usefulness should be influenced by the amount of output as * well as the source type */ static int slow_poll(FILE *dbgfp, int dbgall, size_t *nbytes ) { int moreSources; struct timeval tv; fd_set fds; #if defined( __hpux ) size_t maxFD = 0; #else int maxFD = 0; #endif /* OS-specific brokenness */ int bufPos, i, usefulness = 0; int last_so_far = 0; int any_need_entropy = 0; int delay; int rc; /* Fire up each randomness source */ FD_ZERO(&fds); for (i = 0; dataSources[i].path != NULL; i++) { /* Since popen() is a fairly heavy function, we check to see whether * the executable exists before we try to run it */ if (access(dataSources[i].path, X_OK)) { if( dbgfp && dbgall ) fprintf(dbgfp, "%s not present%s\n", dataSources[i].path, dataSources[i].hasAlternative ? ", has alternatives" : ""); dataSources[i].pipe = NULL; } else dataSources[i].pipe = my_popen(&dataSources[i]); if (dataSources[i].pipe != NULL) { dataSources[i].pipeFD = fileno(dataSources[i].pipe); if (dataSources[i].pipeFD > maxFD) maxFD = dataSources[i].pipeFD; #ifdef O_NONBLOCK /* Ohhh what a hack (used for Atari) */ fcntl(dataSources[i].pipeFD, F_SETFL, O_NONBLOCK); #else #error O_NONBLOCK is missing #endif /* FIXME: We need to make sure that the fd is less than FD_SETSIZE. */ FD_SET(dataSources[i].pipeFD, &fds); dataSources[i].length = 0; /* If there are alternatives for this command, don't try and * execute them */ while (dataSources[i].hasAlternative) { if( dbgfp && dbgall ) fprintf(dbgfp, "Skipping %s\n", dataSources[i + 1].path); i++; } } } /* Suck all the data we can get from each of the sources */ bufPos = 0; moreSources = 1; delay = 0; /* Return immediately (well, after 100ms) the first time. */ while (moreSources && bufPos <= gather_buffer_size) { /* Wait for data to become available from any of the sources, with a * timeout of 10 seconds. This adds even more randomness since data * becomes available in a nondeterministic fashion. Kudos to HP's QA * department for managing to ship a select() which breaks its own * prototype */ tv.tv_sec = delay; tv.tv_usec = delay? 0 : 100000; #if defined( __hpux ) && ( OS_VERSION == 9 ) rc = select(maxFD + 1, (int *)&fds, NULL, NULL, &tv); #else /* */ rc = select(maxFD + 1, &fds, NULL, NULL, &tv); #endif /* __hpux */ if (rc == -1) break; /* Ooops; select failed. */ if (!rc) { /* FIXME: Because we run several tools at once it is unlikely that we will see a block in select at all. */ if (!any_need_entropy || last_so_far != (gather_buffer_size - bufPos) ) { last_so_far = gather_buffer_size - bufPos; _gcry_random_progress ("need_entropy", 'X', last_so_far, gather_buffer_size); any_need_entropy = 1; } delay = 10; /* Use 10 seconds henceforth. */ /* Note that the fd_set is setup again at the end of this loop. */ } /* One of the sources has data available, read it into the buffer */ for (i = 0; dataSources[i].path != NULL; i++) { if( dataSources[i].pipe && FD_ISSET(dataSources[i].pipeFD, &fds)) { size_t noBytes; if ((noBytes = fread(gather_buffer + bufPos, 1, gather_buffer_size - bufPos, dataSources[i].pipe)) == 0) { if (my_pclose(&dataSources[i]) == 0) { int total = 0; /* Try and estimate how much entropy we're getting * from a data source */ if (dataSources[i].usefulness) { if (dataSources[i].usefulness < 0) total = (dataSources[i].length + 999) / -dataSources[i].usefulness; else total = dataSources[i].length / dataSources[i].usefulness; } if( dbgfp ) fprintf(dbgfp, "%s %s contributed %d bytes, " "usefulness = %d\n", dataSources[i].path, (dataSources[i].arg != NULL) ? dataSources[i].arg : "", dataSources[i].length, total); if( dataSources[i].length ) usefulness += total; } dataSources[i].pipe = NULL; } else { int currPos = bufPos; int endPos = bufPos + noBytes; /* Run-length compress the input byte sequence */ while (currPos < endPos) { int ch = gather_buffer[currPos]; /* If it's a single byte, just copy it over */ if (ch != gather_buffer[currPos + 1]) { gather_buffer[bufPos++] = ch; currPos++; } else { int count = 0; /* It's a run of repeated bytes, replace them * with the byte count mod 256 */ while ((ch == gather_buffer[currPos]) && currPos < endPos) { count++; currPos++; } gather_buffer[bufPos++] = count; noBytes -= count - 1; } } /* Remember the number of (compressed) bytes of input we * obtained */ dataSources[i].length += noBytes; } } } /* Check if there is more input available on any of the sources */ moreSources = 0; FD_ZERO(&fds); for (i = 0; dataSources[i].path != NULL; i++) { if (dataSources[i].pipe != NULL) { FD_SET(dataSources[i].pipeFD, &fds); moreSources = 1; } } } if (any_need_entropy) _gcry_random_progress ("need_entropy", 'X', gather_buffer_size, gather_buffer_size); if( dbgfp ) { fprintf(dbgfp, "Got %d bytes, usefulness = %d\n", bufPos, usefulness); fflush(dbgfp); } *nbytes = bufPos; return usefulness; } /**************** * Start the gatherer process which writes messages of * type GATHERER_MSG to pipedes */ static void start_gatherer( int pipefd ) { FILE *dbgfp = NULL; int dbgall; { const char *s = getenv("GCRYPT_RNDUNIX_DBG"); if( s ) { dbgfp = (*s=='-' && !s[1])? stdout : fopen(s, "a"); if( !dbgfp ) log_info("can't open debug file `%s': %s\n", s, strerror(errno) ); else fprintf(dbgfp,"\nSTART RNDUNIX DEBUG pid=%d\n", (int)getpid()); } dbgall = !!getenv("GCRYPT_RNDUNIX_DBGALL"); } /* close all files but the ones we need */ { int nmax, n1, n2, i; #ifdef _SC_OPEN_MAX if( (nmax=sysconf( _SC_OPEN_MAX )) < 0 ) { # ifdef _POSIX_OPEN_MAX nmax = _POSIX_OPEN_MAX; # else nmax = 20; /* assume a reasonable value */ # endif } /* AIX returns INT32_MAX instead of a proper value. We assume that * this is always an error and use a reasonable value. */ # ifdef INT32_MAX if (nmax == INT32_MAX) nmax = 20; # endif #else /*!_SC_OPEN_MAX*/ nmax = 20; /* assume a reasonable value */ #endif /*!_SC_OPEN_MAX*/ n1 = fileno( stderr ); n2 = dbgfp? fileno( dbgfp ) : -1; for(i=0; i < nmax; i++ ) { if( i != n1 && i != n2 && i != pipefd ) close(i); } errno = 0; } /* Set up the buffer. Not ethat we use a plain standard malloc here. */ gather_buffer_size = GATHER_BUFSIZE; gather_buffer = malloc( gather_buffer_size ); if( !gather_buffer ) { log_error("out of core while allocating the gatherer buffer\n"); exit(2); } /* Reset the SIGC(H)LD handler to the system default. This is necessary * because if the program which cryptlib is a part of installs its own * SIGC(H)LD handler, it will end up reaping the cryptlib children before * cryptlib can. As a result, my_pclose() will call waitpid() on a * process which has already been reaped by the installed handler and * return an error, so the read data won't be added to the randomness * pool. There are two types of SIGC(H)LD naming, the SysV SIGCLD and * the BSD/Posix SIGCHLD, so we need to handle either possibility */ #ifdef SIGCLD signal(SIGCLD, SIG_DFL); #else signal(SIGCHLD, SIG_DFL); #endif fclose(stderr); /* Arrghh!! It's Stuart code!! */ /* Mary goes to Berkeley: NetBSD emits warnings if the standard descriptors are not open when running setuid program. Thus we connect them to the bitbucket if they are not already open. */ { struct stat statbuf; if (fstat (STDIN_FILENO, &statbuf) == -1 && errno == EBADF) open ("/dev/null",O_RDONLY); if (fstat (STDOUT_FILENO, &statbuf) == -1 && errno == EBADF) open ("/dev/null",O_WRONLY); if (fstat (STDERR_FILENO, &statbuf) == -1 && errno == EBADF) open ("/dev/null",O_WRONLY); } for(;;) { GATHER_MSG msg; size_t nbytes; const char *p; msg.usefulness = slow_poll( dbgfp, dbgall, &nbytes ); p = (const char*)gather_buffer; while( nbytes ) { msg.ndata = nbytes > sizeof(msg.data)? sizeof(msg.data) : nbytes; memcpy( msg.data, p, msg.ndata ); nbytes -= msg.ndata; p += msg.ndata; while( write( pipefd, &msg, sizeof(msg) ) != sizeof(msg) ) { if( errno == EINTR ) continue; if( errno == EAGAIN ) { struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 50000; select(0, NULL, NULL, NULL, &tv); continue; } if( errno == EPIPE ) /* parent has exited, so give up */ exit(0); /* we can't do very much here because stderr is closed */ if( dbgfp ) fprintf(dbgfp, "gatherer can't write to pipe: %s\n", strerror(errno) ); /* we start a new poll to give the system some time */ nbytes = 0; break; } } } /* we are killed when the parent dies */ } static int read_a_msg( int fd, GATHER_MSG *msg ) { char *buffer = (char*)msg; size_t length = sizeof( *msg ); int n; do { do { n = read(fd, buffer, length ); } while( n == -1 && errno == EINTR ); if( n == -1 ) return -1; buffer += n; length -= n; } while( length ); return 0; } /**************** * Using a level of 0 should never block and better add nothing * to the pool. So this is just a dummy for this gatherer. */ int _gcry_rndunix_gather_random (void (*add)(const void*, size_t, enum random_origins), enum random_origins origin, size_t length, int level ) { static pid_t gatherer_pid = 0; static int pipedes[2]; GATHER_MSG msg; size_t n; if( !level ) return 0; if( !gatherer_pid ) { /* Make sure we are not setuid. */ if ( getuid() != geteuid() ) BUG(); /* time to start the gatherer process */ if( pipe( pipedes ) ) { log_error("pipe() failed: %s\n", strerror(errno)); return -1; } gatherer_pid = fork(); if( gatherer_pid == -1 ) { log_error("can't for gatherer process: %s\n", strerror(errno)); return -1; } if( !gatherer_pid ) { start_gatherer( pipedes[1] ); /* oops, can't happen */ return -1; } } /* now read from the gatherer */ while( length ) { int goodness; ulong subtract; if( read_a_msg( pipedes[0], &msg ) ) { log_error("reading from gatherer pipe failed: %s\n", strerror(errno)); return -1; } if( level > 1 ) { if( msg.usefulness > 30 ) goodness = 100; else if ( msg.usefulness ) goodness = msg.usefulness * 100 / 30; else goodness = 0; } else if( level ) { if( msg.usefulness > 15 ) goodness = 100; else if ( msg.usefulness ) goodness = msg.usefulness * 100 / 15; else goodness = 0; } else goodness = 100; /* goodness of level 0 is always 100 % */ n = msg.ndata; if( n > length ) n = length; (*add)( msg.data, n, origin ); /* this is the trick how we cope with the goodness */ subtract = (ulong)n * goodness / 100; /* subtract at least 1 byte to avoid infinite loops */ length -= subtract ? subtract : 1; } return 0; } diff --git a/random/rndw32.c b/random/rndw32.c index 8c507ac3..1dec5a7e 100644 --- a/random/rndw32.c +++ b/random/rndw32.c @@ -1,1022 +1,1022 @@ /* rndw32.c - W32 entropy gatherer * Copyright (C) 1999, 2000, 2002, 2003, 2007, * 2010 Free Software Foundation, Inc. * Copyright Peter Gutmann, Matt Thomlinson and Blake Coverett 1996-2006 * * This file is part of Libgcrypt. * ************************************************************************* * The code here is based on code from Cryptlib 3.0 beta by Peter Gutmann. * Source file misc/rndwin32.c "Win32 Randomness-Gathering Code" with this * copyright notice: * * This module is part of the cryptlib continuously seeded pseudorandom * number generator. For usage conditions, see lib_rand.c * * [Here is the notice from lib_rand.c, which is now called dev_sys.c] * * This module and the misc/rnd*.c modules represent the cryptlib * continuously seeded pseudorandom number generator (CSPRNG) as described in * my 1998 Usenix Security Symposium paper "The generation of random numbers * for cryptographic purposes". * * The CSPRNG code is copyright Peter Gutmann (and various others) 1996, * 1997, 1998, 1999, all rights reserved. Redistribution of the CSPRNG * modules and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice * and this permission notice in its entirety. * * 2. Redistributions in binary form must reproduce the copyright notice in * the documentation and/or other materials provided with the distribution. * * 3. A copy of any bugfixes or enhancements made must be provided to the * author, to allow them to be added to the * baseline version of the code. * * ALTERNATIVELY, the code may be distributed under the terms of the * GNU Lesser General Public License, version 2.1 or any later version * published by the Free Software Foundation, in which case the * provisions of the GNU LGPL are required INSTEAD OF the above * restrictions. * * Although not required under the terms of the LGPL, it would still * be nice if you could make any changes available to the author to * allow a consistent code base to be maintained. ************************************************************************* * The above alternative was changed from GPL to LGPL on 2007-08-22 with * permission from Peter Gutmann: *========== From: pgut001 Subject: Re: LGPL for the windows entropy gatherer To: wk@gnupg.org Date: Wed, 22 Aug 2007 03:05:42 +1200 Hi, >As of now libgcrypt is GPL under Windows due to that module and some people >would really like to see it under LGPL too. Can you do such a license change >to LGPL version 2? Note that LGPL give the user the option to relicense it >under GPL, so the change would be pretty easy and backwar compatible. Sure. I assumed that since GPG was GPLd, you'd prefer the GPL for the entropy code as well, but Ian asked for LGPL as an option so as of the next release I'll have LGPL in there. You can consider it to be retroactive, so your current version will be LGPLd as well. Peter. *========== */ #include #include #include #include #include #ifdef __GNUC__ #include #endif #include #include #include "types.h" #include "g10lib.h" #include "rand-internal.h" /* Definitions which are missing from the current GNU Windows32Api. */ #ifndef IOCTL_DISK_PERFORMANCE #define IOCTL_DISK_PERFORMANCE 0x00070020 #endif /* This used to be (6*8+5*4+8*2), but Peter Gutmann figured a larger value in a newer release. So we use a far larger value. */ #define SIZEOF_DISK_PERFORMANCE_STRUCT 256 /* We don't include wincrypt.h so define it here. */ #define HCRYPTPROV HANDLE /* When we query the performance counters, we allocate an initial buffer and * then reallocate it as required until RegQueryValueEx() stops returning * ERROR_MORE_DATA. The following values define the initial buffer size and * step size by which the buffer is increased */ #define PERFORMANCE_BUFFER_SIZE 65536 /* Start at 64K */ #define PERFORMANCE_BUFFER_STEP 16384 /* Step by 16K */ /* The number of bytes to read from the system RNG on each slow poll. */ #define SYSTEMRNG_BYTES 64 /* Intel Chipset CSP type and name */ #define PROV_INTEL_SEC 22 #define INTEL_DEF_PROV "Intel Hardware Cryptographic Service Provider" /* Type definitions for function pointers to call NetAPI32 functions. */ typedef DWORD (WINAPI *NETSTATISTICSGET)(LPWSTR szServer, LPWSTR szService, DWORD dwLevel, DWORD dwOptions, LPBYTE *lpBuffer); typedef DWORD (WINAPI *NETAPIBUFFERSIZE)(LPVOID lpBuffer, LPDWORD cbBuffer); typedef DWORD (WINAPI *NETAPIBUFFERFREE)(LPVOID lpBuffer); /* Type definitions for function pointers to call native NT functions. */ typedef DWORD (WINAPI *NTQUERYSYSTEMINFORMATION)(DWORD systemInformationClass, PVOID systemInformation, ULONG systemInformationLength, PULONG returnLength); typedef DWORD (WINAPI *NTQUERYINFORMATIONPROCESS) (HANDLE processHandle, DWORD processInformationClass, PVOID processInformation, ULONG processInformationLength, PULONG returnLength); typedef DWORD (WINAPI *NTPOWERINFORMATION) (DWORD powerInformationClass, PVOID inputBuffer, ULONG inputBufferLength, PVOID outputBuffer, ULONG outputBufferLength ); /* Type definitions for function pointers to call CryptoAPI functions. */ typedef BOOL (WINAPI *CRYPTACQUIRECONTEXT)(HCRYPTPROV *phProv, LPCTSTR pszContainer, LPCTSTR pszProvider, DWORD dwProvType, DWORD dwFlags); typedef BOOL (WINAPI *CRYPTGENRANDOM)(HCRYPTPROV hProv, DWORD dwLen, BYTE *pbBuffer); typedef BOOL (WINAPI *CRYPTRELEASECONTEXT)(HCRYPTPROV hProv, DWORD dwFlags); /* Somewhat alternative functionality available as a direct call, for Windows XP and newer. This is the CryptoAPI RNG, which isn't anywhere near as good as the HW RNG, but we use it if it's present on the basis that at least it can't make things any worse. This direct access version is only available under Windows XP, we don't go out of our way to access the more general CryptoAPI one since the main purpose of using it is to take advantage of any possible future hardware RNGs that may be added, for example via TCPA devices. */ typedef BOOL (WINAPI *RTLGENRANDOM)(PVOID RandomBuffer, ULONG RandomBufferLength); /* MBM data structures, originally by Alexander van Kaam, converted to C by Anders@Majland.org, finally updated by Chris Zahrt */ #define BusType char #define SMBType char #define SensorType char typedef struct { SensorType iType; /* Type of sensor. */ int Count; /* Number of sensor for that type. */ } SharedIndex; typedef struct { SensorType ssType; /* Type of sensor */ unsigned char ssName[12]; /* Name of sensor */ char sspadding1[3]; /* Padding of 3 bytes */ double ssCurrent; /* Current value */ double ssLow; /* Lowest readout */ double ssHigh; /* Highest readout */ long ssCount; /* Total number of readout */ char sspadding2[4]; /* Padding of 4 bytes */ - long double ssTotal; /* Total amout of all readouts */ + long double ssTotal; /* Total amount of all readouts */ char sspadding3[6]; /* Padding of 6 bytes */ double ssAlarm1; /* Temp & fan: high alarm; voltage: % off */ double ssAlarm2; /* Temp: low alarm */ } SharedSensor; typedef struct { short siSMB_Base; /* SMBus base address */ BusType siSMB_Type; /* SMBus/Isa bus used to access chip */ SMBType siSMB_Code; /* SMBus sub type, Intel, AMD or ALi */ char siSMB_Addr; /* Address of sensor chip on SMBus */ unsigned char siSMB_Name[41]; /* Nice name for SMBus */ short siISA_Base; /* ISA base address of sensor chip on ISA */ int siChipType; /* Chip nr, connects with Chipinfo.ini */ char siVoltageSubType; /* Subvoltage option selected */ } SharedInfo; typedef struct { double sdVersion; /* Version number (example: 51090) */ SharedIndex sdIndex[10]; /* Sensor index */ SharedSensor sdSensor[100]; /* Sensor info */ SharedInfo sdInfo; /* Misc.info */ unsigned char sdStart[41]; /* Start time */ /* We don't use the next two fields both because they're not random and because it provides a nice safety margin in case of data size mis- estimates (we always under-estimate the buffer size). */ #if 0 unsigned char sdCurrent[41]; /* Current time */ unsigned char sdPath[256]; /* MBM path */ #endif /*0*/ } SharedData; -/* One time intialized handles and function pointers. We use dynamic +/* One time initialized handles and function pointers. We use dynamic loading of the DLLs to do without them in case libgcrypt does not need any random. */ static HANDLE hNetAPI32; static NETSTATISTICSGET pNetStatisticsGet; static NETAPIBUFFERSIZE pNetApiBufferSize; static NETAPIBUFFERFREE pNetApiBufferFree; static HANDLE hNTAPI; static NTQUERYSYSTEMINFORMATION pNtQuerySystemInformation; static NTQUERYINFORMATIONPROCESS pNtQueryInformationProcess; static NTPOWERINFORMATION pNtPowerInformation; static HANDLE hAdvAPI32; static CRYPTACQUIRECONTEXT pCryptAcquireContext; static CRYPTGENRANDOM pCryptGenRandom; static CRYPTRELEASECONTEXT pCryptReleaseContext; static RTLGENRANDOM pRtlGenRandom; /* Other module global variables. */ static int system_rng_available; /* Whether a system RNG is available. */ static HCRYPTPROV hRNGProv; /* Handle to Intel RNG CSP. */ /* The debug flag. Debugging is enabled if the value of the envvar - * GCRY_RNDW32_DBG is a postive number.*/ + * GCRY_RNDW32_DBG is a positive number.*/ static int debug_me; static int system_is_w2000; /* True if running on W2000. */ /* Try and connect to the system RNG if there's one present. */ static void init_system_rng (void) { system_rng_available = 0; hRNGProv = NULL; hAdvAPI32 = GetModuleHandle ("AdvAPI32.dll"); if (!hAdvAPI32) return; pCryptAcquireContext = (CRYPTACQUIRECONTEXT) GetProcAddress (hAdvAPI32, "CryptAcquireContextA"); pCryptGenRandom = (CRYPTGENRANDOM) GetProcAddress (hAdvAPI32, "CryptGenRandom"); pCryptReleaseContext = (CRYPTRELEASECONTEXT) GetProcAddress (hAdvAPI32, "CryptReleaseContext"); /* Get a pointer to the native randomness function if it's available. This isn't exported by name, so we have to get it by ordinal. */ pRtlGenRandom = (RTLGENRANDOM) GetProcAddress (hAdvAPI32, "SystemFunction036"); /* Try and connect to the PIII RNG CSP. The AMD 768 southbridge (from the 760 MP chipset) also has a hardware RNG, but there doesn't appear to be any driver support for this as there is for the Intel RNG so we can't do much with it. OTOH the Intel RNG is also effectively dead as well, mostly due to virtually nonexistent support/marketing by Intel, it's included here mostly for form's sake. */ if ( (!pCryptAcquireContext || !pCryptGenRandom || !pCryptReleaseContext || !pCryptAcquireContext (&hRNGProv, NULL, INTEL_DEF_PROV, PROV_INTEL_SEC, 0) ) && !pRtlGenRandom) { hAdvAPI32 = NULL; } else system_rng_available = 1; } /* Read data from the system RNG if availavle. */ static void read_system_rng (void (*add)(const void*, size_t, enum random_origins), enum random_origins requester) { BYTE buffer[ SYSTEMRNG_BYTES + 8 ]; int quality = 0; if (!system_rng_available) return; /* Read SYSTEMRNG_BYTES bytes from the system RNG. We don't rely on this for all our randomness requirements (particularly the software RNG) in case it's broken in some way. */ if (hRNGProv) { if (pCryptGenRandom (hRNGProv, SYSTEMRNG_BYTES, buffer)) quality = 80; } else if (pRtlGenRandom) { if ( pRtlGenRandom (buffer, SYSTEMRNG_BYTES)) quality = 50; } if (quality > 0) { if (debug_me) log_debug ("rndw32#read_system_rng: got %d bytes of quality %d\n", SYSTEMRNG_BYTES, quality); (*add) (buffer, SYSTEMRNG_BYTES, requester); wipememory (buffer, SYSTEMRNG_BYTES); } } /* Read data from MBM. This communicates via shared memory, so all we need to do is map a file and read the data out. */ static void read_mbm_data (void (*add)(const void*, size_t, enum random_origins), enum random_origins requester) { HANDLE hMBMData; SharedData *mbmDataPtr; hMBMData = OpenFileMapping (FILE_MAP_READ, FALSE, "$M$B$M$5$S$D$" ); if (hMBMData) { mbmDataPtr = (SharedData*)MapViewOfFile (hMBMData, FILE_MAP_READ,0,0,0); if (mbmDataPtr) { if (debug_me) log_debug ("rndw32#read_mbm_data: got %d bytes\n", (int)sizeof (SharedData)); (*add) (mbmDataPtr, sizeof (SharedData), requester); UnmapViewOfFile (mbmDataPtr); } CloseHandle (hMBMData); } } /* Fallback method using the registry to poll the statistics. */ static void registry_poll (void (*add)(const void*, size_t, enum random_origins), enum random_origins requester) { static int cbPerfData = PERFORMANCE_BUFFER_SIZE; int iterations; DWORD dwSize, status; PERF_DATA_BLOCK *pPerfData; /* Get information from the system performance counters. This can take a few seconds to do. In some environments the call to RegQueryValueEx() can produce an access violation at some random time in the future, in some cases adding a short delay after the following code block makes the problem go away. This problem is extremely difficult to reproduce, I haven't been able to get it to occur despite running it on a number of machines. MS knowledge base article Q178887 covers this type of problem, it's typically caused by an external driver or other program that adds its own values under the HKEY_PERFORMANCE_DATA key. The NT kernel, via Advapi32.dll, calls the required external module to map in the data inside an SEH try/except block, so problems in the module's collect function don't pop up until after it has finished, so the fault appears to occur in Advapi32.dll. There may be problems in the NT kernel as well though, a low-level memory checker indicated that ExpandEnvironmentStrings() in Kernel32.dll, called an interminable number of calls down inside RegQueryValueEx(), was overwriting memory (it wrote twice the allocated size of a buffer to a buffer allocated by the NT kernel). OTOH this could be coming from the external module calling back into the kernel, which eventually causes the problem described above. Possibly as an extension of the problem that the krnlWaitSemaphore() call above works around, running two instances of cryptlib (e.g. two applications that use it) under NT4 can result in one of them hanging in the RegQueryValueEx() call. This happens only under NT4 and is hard to reproduce in any consistent manner. One workaround that helps a bit is to read the registry as a remote (rather than local) registry, it's possible that the use of a network RPC call isolates the calling app from the problem in that whatever service handles the RPC is taking the hit and not affecting the calling app. Since this would require another round of extensive testing to verify and the NT native API call is working fine, we'll stick with the native API call for now. Some versions of NT4 had a problem where the amount of data returned was mis-reported and would never settle down, because of this the code below includes a safety-catch that bails out after 10 attempts have been made, this results in no data being returned but at does ensure that the thread will terminate. In addition to these problems the code in RegQueryValueEx() that estimates the amount of memory required to return the performance counter information isn't very accurate (it's much worse than the "slightly-inaccurate" level that the MS docs warn about, it's usually wildly off) since it always returns a worst-case estimate which is usually nowhere near the actual amount required. For example it may report that 128K of memory is required, but only return 64K of data. Even worse than the registry-based performance counters is the performance data helper (PDH) shim that tries to make the counters look like the old Win16 API (which is also used by Win95). Under NT this can consume tens of MB of memory and huge amounts of CPU time while it gathers its data, and even running once can still consume about 1/2MB of memory */ if (getenv ("GCRYPT_RNDW32_NOPERF")) { static int shown; if (!shown) { shown = 1; log_info ("note: get performance data has been disabled\n"); } } else { pPerfData = xmalloc (cbPerfData); for (iterations=0; iterations < 10; iterations++) { dwSize = cbPerfData; if ( debug_me ) log_debug ("rndw32#slow_gatherer_nt: get perf data\n" ); status = RegQueryValueEx (HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, (LPBYTE) pPerfData, &dwSize); if (status == ERROR_SUCCESS) { if (!memcmp (pPerfData->Signature, L"PERF", 8)) (*add) ( pPerfData, dwSize, requester ); else log_debug ("rndw32: no PERF signature\n"); break; } else if (status == ERROR_MORE_DATA) { cbPerfData += PERFORMANCE_BUFFER_STEP; pPerfData = xrealloc (pPerfData, cbPerfData); } else { static int been_here; /* Silence the error message. In particular under Wine (as of 2008) we would get swamped with such diagnotiscs. One such diagnotiscs should be enough. */ if (been_here != status) { been_here = status; log_debug ("rndw32: get performance data problem: ec=%ld\n", status); } break; } } xfree (pPerfData); } /* Although this isn't documented in the Win32 API docs, it's necessary to explicitly close the HKEY_PERFORMANCE_DATA key after use (it's implicitly opened on the first call to RegQueryValueEx()). If this isn't done then any system components which provide performance data can't be removed or changed while the handle remains active. */ RegCloseKey (HKEY_PERFORMANCE_DATA); } static void slow_gatherer ( void (*add)(const void*, size_t, enum random_origins), enum random_origins requester ) { static int is_initialized = 0; static int is_workstation = 1; HANDLE hDevice; DWORD dwType, dwSize, dwResult; ULONG ulSize; int drive_no, status; int no_results = 0; void *buffer; if ( !is_initialized ) { HKEY hKey; if ( debug_me ) log_debug ("rndw32#slow_gatherer: init toolkit\n" ); /* Find out whether this is an NT server or workstation if necessary */ if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Control\\ProductOptions", 0, KEY_READ, &hKey) == ERROR_SUCCESS) { BYTE szValue[32 + 8]; dwSize = 32; if ( debug_me ) log_debug ("rndw32#slow_gatherer: check product options\n" ); status = RegQueryValueEx (hKey, "ProductType", 0, NULL, szValue, &dwSize); if (status == ERROR_SUCCESS && stricmp ((char*)szValue, "WinNT")) { /* Note: There are (at least) three cases for ProductType: WinNT = NT Workstation, ServerNT = NT Server, LanmanNT = NT Server acting as a Domain Controller. */ is_workstation = 0; if ( debug_me ) log_debug ("rndw32: this is a NT server\n"); } RegCloseKey (hKey); } /* The following are fixed for the lifetime of the process so we only add them once */ /* readPnPData (); - we have not implemented that. */ /* Initialize the NetAPI32 function pointers if necessary */ hNetAPI32 = LoadLibrary ("NETAPI32.DLL"); if (hNetAPI32) { if (debug_me) log_debug ("rndw32#slow_gatherer: netapi32 loaded\n" ); pNetStatisticsGet = (NETSTATISTICSGET) GetProcAddress (hNetAPI32, "NetStatisticsGet"); pNetApiBufferSize = (NETAPIBUFFERSIZE) GetProcAddress (hNetAPI32, "NetApiBufferSize"); pNetApiBufferFree = (NETAPIBUFFERFREE) GetProcAddress (hNetAPI32, "NetApiBufferFree"); if (!pNetStatisticsGet || !pNetApiBufferSize || !pNetApiBufferFree) { FreeLibrary (hNetAPI32); hNetAPI32 = NULL; log_debug ("rndw32: No NETAPI found\n" ); } } /* Initialize the NT kernel native API function pointers if necessary */ hNTAPI = GetModuleHandle ("NTDll.dll"); if (hNTAPI) { /* Get a pointer to the NT native information query functions */ pNtQuerySystemInformation = (NTQUERYSYSTEMINFORMATION) GetProcAddress (hNTAPI, "NtQuerySystemInformation"); pNtQueryInformationProcess = (NTQUERYINFORMATIONPROCESS) GetProcAddress (hNTAPI, "NtQueryInformationProcess"); pNtPowerInformation = (NTPOWERINFORMATION) GetProcAddress(hNTAPI, "NtPowerInformation"); if (!pNtQuerySystemInformation || !pNtQueryInformationProcess) hNTAPI = NULL; } is_initialized = 1; } read_system_rng ( add, requester ); read_mbm_data ( add, requester ); /* Get network statistics. Note: Both NT Workstation and NT Server by default will be running both the workstation and server services. The heuristic below is probably useful though on the assumption that the majority of the network traffic will be via the appropriate service. In any case the network statistics return almost no randomness. */ { LPBYTE lpBuffer; if (hNetAPI32 && !pNetStatisticsGet (NULL, is_workstation ? L"LanmanWorkstation" : L"LanmanServer", 0, 0, &lpBuffer)) { if ( debug_me ) log_debug ("rndw32#slow_gatherer: get netstats\n" ); pNetApiBufferSize (lpBuffer, &dwSize); (*add) ( lpBuffer, dwSize, requester ); pNetApiBufferFree (lpBuffer); } } /* Get disk I/O statistics for all the hard drives. 100 is an arbitrary failsafe limit. */ for (drive_no = 0; drive_no < 100 ; drive_no++) { char diskPerformance[SIZEOF_DISK_PERFORMANCE_STRUCT + 8]; char szDevice[50]; /* Check whether we can access this device. */ snprintf (szDevice, sizeof szDevice, "\\\\.\\PhysicalDrive%d", drive_no); hDevice = CreateFile (szDevice, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); if (hDevice == INVALID_HANDLE_VALUE) break; /* No more drives. */ /* Note: This only works if you have turned on the disk performance counters with 'diskperf -y'. These counters are off by default. */ dwSize = sizeof diskPerformance; if (DeviceIoControl (hDevice, IOCTL_DISK_PERFORMANCE, NULL, 0, diskPerformance, SIZEOF_DISK_PERFORMANCE_STRUCT, &dwSize, NULL)) { if ( debug_me ) log_debug ("rndw32#slow_gatherer: iostat drive %d\n", drive_no); (*add) (diskPerformance, dwSize, requester); } else { log_info ("NOTE: you should run 'diskperf -y' " "to enable the disk statistics\n"); } CloseHandle (hDevice); } /* In theory we should be using the Win32 performance query API to obtain unpredictable data from the system, however this is so unreliable (see the multiple sets of comments in registryPoll()) that it's too risky to rely on it except as a fallback in emergencies. Instead, we rely mostly on the NT native API function NtQuerySystemInformation(), which has the dual advantages that it doesn't have as many (known) problems as the Win32 equivalent and that it doesn't access the data indirectly via pseudo-registry keys, which means that it's much faster. Note that the Win32 equivalent actually works almost all of the time, the problem is that on one or two systems it can fail in strange ways that are never the same and can't be reproduced on any other system, which is why we use the native API here. Microsoft officially documented this function in early 2003, so it'll be fairly safe to use. */ if ( !hNTAPI ) { registry_poll (add, requester); return; } /* Scan the first 64 possible information types (we don't bother with increasing the buffer size as we do with the Win32 version of the performance data read, we may miss a few classes but it's no big deal). This scan typically yields around 20 pieces of data, there's nothing in the range 65...128 so chances are there won't be anything above there either. */ buffer = xmalloc (PERFORMANCE_BUFFER_SIZE); for (dwType = 0; dwType < 64; dwType++) { switch (dwType) { /* ID 17 = SystemObjectInformation hangs on some win2k systems. */ case 17: if (system_is_w2000) continue; break; /* Some information types are write-only (the IDs are shared with a set-information call), we skip these. */ case 26: case 27: case 38: case 46: case 47: case 48: case 52: continue; /* ID 53 = SystemSessionProcessInformation reads input from the output buffer, which has to contain a session ID and pointer to the actual buffer in which to store the session information. Because this isn't a standard query, we skip this. */ case 53: continue; } /* Query the info for this ID. Some results (for example for ID = 6, SystemCallCounts) are only available in checked builds of the kernel. A smaller subcless of results require that certain system config flags be set, for example SystemObjectInformation requires that the FLG_MAINTAIN_OBJECT_TYPELIST be set in NtGlobalFlags. To avoid having to special-case all of these, we try reading each one and only use those for which we get a success status. */ dwResult = pNtQuerySystemInformation (dwType, buffer, PERFORMANCE_BUFFER_SIZE - 2048, &ulSize); if (dwResult != ERROR_SUCCESS) continue; /* Some calls (e.g. ID = 23, SystemProcessorStatistics, and ID = 24, SystemDpcInformation) incorrectly return a length of zero, so we manually adjust the length to the correct value. */ if ( !ulSize ) { if (dwType == 23) ulSize = 6 * sizeof (ULONG); else if (dwType == 24) ulSize = 5 * sizeof (ULONG); } /* If we got some data back, add it to the entropy pool. */ if (ulSize > 0 && ulSize <= PERFORMANCE_BUFFER_SIZE - 2048) { if (debug_me) log_debug ("rndw32#slow_gatherer: %lu bytes from sysinfo %ld\n", ulSize, dwType); (*add) (buffer, ulSize, requester); no_results++; } } /* Now we would do the same for the process information. This call would rather ugly in that it requires an exact length match for the data returned, failing with a STATUS_INFO_LENGTH_MISMATCH error code (0xC0000004) if the length isn't an exact match. It requires a compiler to handle complex nested structs, alignment issues, and so on, and without the headers in which the entries are declared it's almost impossible to do. Thus we don't. */ /* Finally, do the same for the system power status information. There are only a limited number of useful information types available so we restrict ourselves to the useful types. In addition since this function doesn't return length information, we have to hardcode in length data. */ if (pNtPowerInformation) { static const struct { int type; int size; } powerInfo[] = { { 0, 128 }, /* SystemPowerPolicyAc */ { 1, 128 }, /* SystemPowerPolicyDc */ { 4, 64 }, /* SystemPowerCapabilities */ { 5, 48 }, /* SystemBatteryState */ { 11, 48 }, /* ProcessorInformation */ { 12, 24 }, /* SystemPowerInformation */ { -1, -1 } }; int i; /* The 100 is a failsafe limit. */ for (i = 0; powerInfo[i].type != -1 && i < 100; i++ ) { /* Query the info for this ID */ dwResult = pNtPowerInformation (powerInfo[i].type, NULL, 0, buffer, PERFORMANCE_BUFFER_SIZE - 2048); if (dwResult != ERROR_SUCCESS) continue; if (debug_me) log_debug ("rndw32#slow_gatherer: %u bytes from powerinfo %d\n", powerInfo[i].size, i); (*add) (buffer, powerInfo[i].size, requester); no_results++; } gcry_assert (i < 100); } xfree (buffer); /* We couldn't get enough results from the kernel, fall back to the somewhat troublesome registry poll. */ if (no_results < 15) registry_poll (add, requester); } int _gcry_rndw32_gather_random (void (*add)(const void*, size_t, enum random_origins), enum random_origins origin, size_t length, int level ) { static int is_initialized; if (!level) return 0; /* We don't differentiate between level 1 and 2 here because there is no internal entropy pool as a scary resource. It may all work slower, but because our entropy source will never block but deliver some not easy to measure entropy, we assume level 2. */ if (!is_initialized) { OSVERSIONINFO osvi = { sizeof( osvi ) }; const char *s; if ((s = getenv ("GCRYPT_RNDW32_DBG")) && atoi (s) > 0) debug_me = 1; GetVersionEx( &osvi ); if (osvi.dwPlatformId != VER_PLATFORM_WIN32_NT) log_fatal ("can only run on a Windows NT platform\n" ); system_is_w2000 = (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0); init_system_rng (); is_initialized = 1; } if (debug_me) log_debug ("rndw32#gather_random: ori=%d len=%u lvl=%d\n", origin, (unsigned int)length, level ); slow_gatherer (add, origin); return 0; } void _gcry_rndw32_gather_random_fast (void (*add)(const void*, size_t, enum random_origins), enum random_origins origin) { static int addedFixedItems = 0; if ( debug_me ) log_debug ("rndw32#gather_random_fast: ori=%d\n", origin ); /* Get various basic pieces of system information: Handle of active window, handle of window with mouse capture, handle of clipboard owner handle of start of clpboard viewer list, pseudohandle of current process, current process ID, pseudohandle of current thread, current thread ID, handle of desktop window, handle of window with keyboard focus, whether system queue has any events, cursor position for last message, 1 ms time for last message, handle of window with clipboard open, handle of process heap, handle of procs window station, types of events in input queue, and milliseconds since Windows was started. On 64-bit platform some of these return values are pointers and thus 64-bit wide. We discard the upper 32-bit of those values. */ { byte buffer[20*sizeof(ulong)], *bufptr; bufptr = buffer; #define ADDINT(f) do { ulong along = (ulong)(f); \ memcpy (bufptr, &along, sizeof (along) ); \ bufptr += sizeof (along); \ } while (0) #define ADDPTR(f) do { void *aptr = (f); \ ADDINT((SIZE_T)aptr); \ } while (0) ADDPTR ( GetActiveWindow ()); ADDPTR ( GetCapture ()); ADDPTR ( GetClipboardOwner ()); ADDPTR ( GetClipboardViewer ()); ADDPTR ( GetCurrentProcess ()); ADDINT ( GetCurrentProcessId ()); ADDPTR ( GetCurrentThread ()); ADDINT ( GetCurrentThreadId ()); ADDPTR ( GetDesktopWindow ()); ADDPTR ( GetFocus ()); ADDINT ( GetInputState ()); ADDINT ( GetMessagePos ()); ADDINT ( GetMessageTime ()); ADDPTR ( GetOpenClipboardWindow ()); ADDPTR ( GetProcessHeap ()); ADDPTR ( GetProcessWindowStation ()); /* Following function in some cases stops returning events, and cannot be used as an entropy source. */ /*ADDINT ( GetQueueStatus (QS_ALLEVENTS));*/ ADDINT ( GetTickCount ()); gcry_assert ( bufptr-buffer < sizeof (buffer) ); (*add) ( buffer, bufptr-buffer, origin ); #undef ADDINT #undef ADDPTR } /* Get multiword system information: Current caret position, current mouse cursor position. */ { POINT point; GetCaretPos (&point); (*add) ( &point, sizeof (point), origin ); GetCursorPos (&point); (*add) ( &point, sizeof (point), origin ); } /* Get percent of memory in use, bytes of physical memory, bytes of free physical memory, bytes in paging file, free bytes in paging file, user bytes of address space, and free user bytes. */ { MEMORYSTATUS memoryStatus; memoryStatus.dwLength = sizeof (MEMORYSTATUS); GlobalMemoryStatus (&memoryStatus); (*add) ( &memoryStatus, sizeof (memoryStatus), origin ); } /* Get thread and process creation time, exit time, time in kernel mode, and time in user mode in 100ns intervals. */ { HANDLE handle; FILETIME creationTime, exitTime, kernelTime, userTime; SIZE_T minimumWorkingSetSize, maximumWorkingSetSize; handle = GetCurrentThread (); GetThreadTimes (handle, &creationTime, &exitTime, &kernelTime, &userTime); (*add) ( &creationTime, sizeof (creationTime), origin ); (*add) ( &exitTime, sizeof (exitTime), origin ); (*add) ( &kernelTime, sizeof (kernelTime), origin ); (*add) ( &userTime, sizeof (userTime), origin ); handle = GetCurrentProcess (); GetProcessTimes (handle, &creationTime, &exitTime, &kernelTime, &userTime); (*add) ( &creationTime, sizeof (creationTime), origin ); (*add) ( &exitTime, sizeof (exitTime), origin ); (*add) ( &kernelTime, sizeof (kernelTime), origin ); (*add) ( &userTime, sizeof (userTime), origin ); /* Get the minimum and maximum working set size for the current process. */ GetProcessWorkingSetSize (handle, &minimumWorkingSetSize, &maximumWorkingSetSize); /* On 64-bit system, discard the high 32-bits. */ (*add) ( &minimumWorkingSetSize, sizeof (int), origin ); (*add) ( &maximumWorkingSetSize, sizeof (int), origin ); } /* The following are fixed for the lifetime of the process so we only * add them once */ if (!addedFixedItems) { STARTUPINFO startupInfo; /* Get name of desktop, console window title, new window position and size, window flags, and handles for stdin, stdout, and stderr. */ startupInfo.cb = sizeof (STARTUPINFO); GetStartupInfo (&startupInfo); (*add) ( &startupInfo, sizeof (STARTUPINFO), origin ); addedFixedItems = 1; } /* The performance of QPC varies depending on the architecture it's running on and on the OS, the MS documentation is vague about the details because it varies so much. Under Win9x/ME it reads the 1.193180 MHz PIC timer. Under NT/Win2K/XP it may or may not read the 64-bit TSC depending on the HAL and assorted other circumstances, generally on machines with a uniprocessor HAL KeQueryPerformanceCounter() uses a 3.579545MHz timer and on machines with a multiprocessor or APIC HAL it uses the TSC (the exact time source is controlled by the HalpUse8254 flag in the kernel). That choice of time sources is somewhat peculiar because on a multiprocessor machine it's theoretically possible to get completely different TSC readings depending on which CPU you're currently running on, while for uniprocessor machines it's not a problem. However, the kernel appears to synchronise the TSCs across CPUs at boot time (it resets the TSC as part of its system init), so this shouldn't really be a problem. Under WinCE it's completely platform- dependent, if there's no hardware performance counter available, it uses the 1ms system timer. Another feature of the TSC (although it doesn't really affect us here) is that mobile CPUs will turn off the TSC when they idle, Pentiums will change the rate of the counter when they clock-throttle (to match the current CPU speed), and hyperthreading Pentiums will turn it off when both threads are idle (this more or less makes sense, since the CPU will be in the halted state and not executing any instructions to count). To make things unambiguous, we detect a CPU new enough to call RDTSC directly by checking for CPUID capabilities, and fall back to QPC if this isn't present. On AMD64, TSC is always available and intrinsic is provided for accessing it. */ #ifdef __WIN64__ { unsigned __int64 aint64; /* Note: cryptlib does not discard upper 32 bits of TSC on WIN64, but does * on WIN32. Is this correct? */ aint64 = __rdtsc(); (*add) (&aint64, sizeof(aint64), origin); } #else #ifdef __GNUC__ /* FIXME: We would need to implement the CPU feature tests first. */ /* if (cpu_has_feature_rdtsc) */ /* { */ /* uint32_t lo, hi; */ /* We cannot use "=A", since this would use %rax on x86_64. */ /* __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi)); */ /* Ignore high 32 bits, hwich are >1s res. */ /* (*add) (&lo, 4, origin ); */ /* } */ /* else */ #endif /*!__GNUC__*/ { LARGE_INTEGER performanceCount; if (QueryPerformanceCounter (&performanceCount)) { if ( debug_me ) log_debug ("rndw32#gather_random_fast: perf data\n"); (*add) (&performanceCount, sizeof (performanceCount), origin); } else { /* Millisecond accuracy at best... */ DWORD aword = GetTickCount (); (*add) (&aword, sizeof (aword), origin ); } } #endif /*__WIN64__*/ } diff --git a/src/gcrypt.h.in b/src/gcrypt.h.in index 5727abba..8e499672 100644 --- a/src/gcrypt.h.in +++ b/src/gcrypt.h.in @@ -1,1793 +1,1793 @@ /* gcrypt.h - GNU Cryptographic Library Interface -*- c -*- * Copyright (C) 1998-2016 Free Software Foundation, Inc. * Copyright (C) 2012-2016 g10 Code GmbH * * 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 . * * File: @configure_input@ */ #ifndef _GCRYPT_H #define _GCRYPT_H #include #include #include #include #include #if defined _WIN32 || defined __WIN32__ # include # include # include # ifndef __GNUC__ typedef long ssize_t; typedef int pid_t; # endif /*!__GNUC__*/ #else # include # include #@INSERT_SYS_SELECT_H@ #endif /*!_WIN32*/ @FALLBACK_SOCKLEN_T@ /* 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@" /* The version number of this header. It may be used to handle minor API incompatibilities. */ #define GCRYPT_VERSION_NUMBER @VERSION_NUMBER@ /* 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 #define _GCRY_GCC_ATTR_PRINTF(f,a) __attribute__ ((format (printf,f,a))) #if _GCRY_GCC_VERSION >= 40000 #define _GCRY_GCC_ATTR_SENTINEL(a) __attribute__ ((sentinel(a))) #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 #ifndef _GCRY_GCC_ATTR_PRINTF #define _GCRY_GCC_ATTR_PRINTF(f,a) #endif #ifndef _GCRY_GCC_ATTR_SENTINEL #define _GCRY_GCC_ATTR_SENTINEL(a) #endif /* Make up an attribute to mark functions and types as deprecated but allow internal use by Libgcrypt. */ #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); /* NOTE: Since Libgcrypt 1.6 the thread callbacks are not anymore used. However we keep it to allow for some source code compatibility if used in the standard way. */ /* 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 1 /* 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; } _GCRY_ATTR_INTERNAL; #define GCRY_THREAD_OPTION_PTH_IMPL \ static struct gcry_thread_cbs gcry_threads_pth = { \ (GCRY_THREAD_OPTION_PTH | (GCRY_THREAD_OPTION_VERSION << 8))} #define GCRY_THREAD_OPTION_PTHREAD_IMPL \ static struct gcry_thread_cbs gcry_threads_pthread = { \ (GCRY_THREAD_OPTION_PTHREAD | (GCRY_THREAD_OPTION_VERSION << 8))} /* A generic context object as used by some functions. */ struct gcry_context; typedef struct gcry_context *gcry_ctx_t; /* The data objects used to hold multi precision integers. */ struct gcry_mpi; typedef struct gcry_mpi *gcry_mpi_t; struct gcry_mpi_point; typedef struct gcry_mpi_point *gcry_mpi_point_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 /* A structure used for scatter gather hashing. */ typedef struct { size_t size; /* The allocated size of the buffer or 0. */ size_t off; /* Offset into the buffer. */ size_t len; /* The used length of the buffer. */ void *data; /* The buffer. */ } gcry_buffer_t; /* 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 { /* Note: 1 .. 2 are not anymore used. */ 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, /* Note: 43 is not anymore used. */ 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 .. 62 are used internally. */ GCRYCTL_DISABLE_HWF = 63, GCRYCTL_SET_ENFORCED_FIPS_FLAG = 64, GCRYCTL_SET_PREFERRED_RNG_TYPE = 65, GCRYCTL_GET_CURRENT_RNG_TYPE = 66, GCRYCTL_DISABLE_LOCKED_SECMEM = 67, GCRYCTL_DISABLE_PRIV_DROP = 68, GCRYCTL_SET_CCM_LENGTHS = 69, GCRYCTL_CLOSE_RANDOM_DEVICE = 70, GCRYCTL_INACTIVATE_FIPS_FLAG = 71, GCRYCTL_REACTIVATE_FIPS_FLAG = 72, GCRYCTL_SET_SBOX = 73, GCRYCTL_DRBG_REINIT = 74, GCRYCTL_SET_TAGLEN = 75, GCRYCTL_GET_TAGLEN = 76, GCRYCTL_REINIT_SYSCALL_CLAMP = 77 }; /* 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 +/* Calculate the length of an canonized S-expression 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 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 data from a LIST. A malloced buffer to the data with index NUMBER is returned and the length of this data will be stored to RLENGTH. If there is no data at the given index or the index represents another list, `NULL' is returned. */ void *gcry_sexp_nth_buffer (const gcry_sexp_t list, int number, size_t *rlength); /* 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); /* Extract MPIs from an s-expression using a list of parameters. The * names of these parameters are given by the string LIST. Some * special characters may be given to control the conversion: * * + :: Switch to unsigned integer format (default). * - :: Switch to standard signed format. * / :: Switch to opaque format. * & :: Switch to buffer descriptor mode - see below. * ? :: The previous parameter is optional. * * In general parameter names are single letters. To use a string for * a parameter name, enclose the name in single quotes. * * Unless in gcry_buffer_t mode for each parameter name a pointer to * an MPI variable is expected that must be set to NULL prior to * invoking this function, and finally a NULL is expected. Example: * * _gcry_sexp_extract_param (key, NULL, "n/x+ed", * &mpi_n, &mpi_x, &mpi_e, NULL) * * This stores the parameter "N" from KEY as an unsigned MPI into * MPI_N, the parameter "X" as an opaque MPI into MPI_X, and the * parameter "E" again as an unsigned MPI into MPI_E. * * If in buffer descriptor mode a pointer to gcry_buffer_t descriptor * is expected instead of a pointer to an MPI. The caller may use two * different operation modes: If the DATA field of the provided buffer * descriptor is NULL, the function allocates a new buffer and stores * it at DATA; the other fields are set accordingly with OFF being 0. * If DATA is not NULL, the function assumes that DATA, SIZE, and OFF * describe a buffer where to but the data; on return the LEN field * receives the number of bytes copied to that buffer; if the buffer * is too small, the function immediately returns with an error code * (and LEN set to 0). * * PATH is an optional string used to locate a token. The exclamation * mark separated tokens are used to via gcry_sexp_find_token to find * a start point inside SEXP. * * The function returns 0 on success. On error an error code is * returned, all passed MPIs that might have been allocated up to this * point are deallocated and set to NULL, and all passed buffers are * either truncated if the caller supplied the buffer, or deallocated * if the function allocated the buffer. */ gpg_error_t gcry_sexp_extract_param (gcry_sexp_t sexp, const char *path, const char *list, ...) _GCRY_GCC_ATTR_SENTINEL(0); /******************************************* * * * 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. */ GCRYMPI_FMT_OPAQUE = 8 /* Opaque format (some functions only). */ }; /* 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. */ GCRYMPI_FLAG_IMMUTABLE = 4, /* Mark the MPI as immutable. */ GCRYMPI_FLAG_CONST = 8, /* Mark the MPI as a constant. */ GCRYMPI_FLAG_USER1 = 0x0100,/* User flag 1. */ GCRYMPI_FLAG_USER2 = 0x0200,/* User flag 2. */ GCRYMPI_FLAG_USER3 = 0x0400,/* User flag 3. */ GCRYMPI_FLAG_USER4 = 0x0800 /* User flag 4. */ }; /* Macros to return pre-defined MPI constants. */ #define GCRYMPI_CONST_ONE (_gcry_mpi_get_const (1)) #define GCRYMPI_CONST_TWO (_gcry_mpi_get_const (2)) #define GCRYMPI_CONST_THREE (_gcry_mpi_get_const (3)) #define GCRYMPI_CONST_FOUR (_gcry_mpi_get_const (4)) #define GCRYMPI_CONST_EIGHT (_gcry_mpi_get_const (8)) /* 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 and release U. */ void gcry_mpi_snatch (gcry_mpi_t w, gcry_mpi_t u); /* 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); /* Return 1 if A is negative; 0 if zero or positive. */ int gcry_mpi_is_neg (gcry_mpi_t a); /* W = - U */ void gcry_mpi_neg (gcry_mpi_t w, gcry_mpi_t u); /* W = [W] */ void gcry_mpi_abs (gcry_mpi_t w); /* 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 into 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); /* Create a new point object. NBITS is usually 0. */ gcry_mpi_point_t gcry_mpi_point_new (unsigned int nbits); /* Release the object POINT. POINT may be NULL. */ void gcry_mpi_point_release (gcry_mpi_point_t point); /* Store the projective coordinates from POINT into X, Y, and Z. */ void gcry_mpi_point_get (gcry_mpi_t x, gcry_mpi_t y, gcry_mpi_t z, gcry_mpi_point_t point); /* Store the projective coordinates from POINT into X, Y, and Z and release POINT. */ void gcry_mpi_point_snatch_get (gcry_mpi_t x, gcry_mpi_t y, gcry_mpi_t z, gcry_mpi_point_t point); /* Store the projective coordinates X, Y, and Z into POINT. */ gcry_mpi_point_t gcry_mpi_point_set (gcry_mpi_point_t point, gcry_mpi_t x, gcry_mpi_t y, gcry_mpi_t z); /* Store the projective coordinates X, Y, and Z into POINT and release X, Y, and Z. */ gcry_mpi_point_t gcry_mpi_point_snatch_set (gcry_mpi_point_t point, gcry_mpi_t x, gcry_mpi_t y, gcry_mpi_t z); /* Allocate a new context for elliptic curve operations based on the parameters given by KEYPARAM or using CURVENAME. */ gpg_error_t gcry_mpi_ec_new (gcry_ctx_t *r_ctx, gcry_sexp_t keyparam, const char *curvename); /* Get a named MPI from an elliptic curve context. */ gcry_mpi_t gcry_mpi_ec_get_mpi (const char *name, gcry_ctx_t ctx, int copy); /* Get a named point from an elliptic curve context. */ gcry_mpi_point_t gcry_mpi_ec_get_point (const char *name, gcry_ctx_t ctx, int copy); /* Store a named MPI into an elliptic curve context. */ gpg_error_t gcry_mpi_ec_set_mpi (const char *name, gcry_mpi_t newvalue, gcry_ctx_t ctx); /* Store a named point into an elliptic curve context. */ gpg_error_t gcry_mpi_ec_set_point (const char *name, gcry_mpi_point_t newvalue, gcry_ctx_t ctx); /* Decode and store VALUE into RESULT. */ gpg_error_t gcry_mpi_ec_decode_point (gcry_mpi_point_t result, gcry_mpi_t value, gcry_ctx_t ctx); /* Store the affine coordinates of POINT into X and Y. */ int gcry_mpi_ec_get_affine (gcry_mpi_t x, gcry_mpi_t y, gcry_mpi_point_t point, gcry_ctx_t ctx); /* W = 2 * U. */ void gcry_mpi_ec_dup (gcry_mpi_point_t w, gcry_mpi_point_t u, gcry_ctx_t ctx); /* W = U + V. */ void gcry_mpi_ec_add (gcry_mpi_point_t w, gcry_mpi_point_t u, gcry_mpi_point_t v, gcry_ctx_t ctx); /* W = U - V. */ void gcry_mpi_ec_sub (gcry_mpi_point_t w, gcry_mpi_point_t u, gcry_mpi_point_t v, gcry_ctx_t ctx); /* W = N * U. */ void gcry_mpi_ec_mul (gcry_mpi_point_t w, gcry_mpi_t n, gcry_mpi_point_t u, gcry_ctx_t ctx); /* Return true if POINT is on the curve described by CTX. */ int gcry_mpi_ec_curve_point (gcry_mpi_point_t w, gcry_ctx_t ctx); /* 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. On success A received the the ownership of the value P. WARNING: Never use an opaque MPI for anything thing else than gcry_mpi_release, gcry_mpi_get_opaque. */ gcry_mpi_t gcry_mpi_set_opaque (gcry_mpi_t a, void *p, unsigned int nbits); /* Store NBITS of the value P points to in A and mark A as an opaque value. The function takes a copy of the provided value P. WARNING: Never use an opaque MPI for anything thing else than gcry_mpi_release, gcry_mpi_get_opaque. */ gcry_mpi_t gcry_mpi_set_opaque_copy (gcry_mpi_t a, const 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 if the FLAG is set for A. */ int gcry_mpi_get_flag (gcry_mpi_t a, enum gcry_mpi_flag flag); /* Private function - do not use. */ gcry_mpi_t _gcry_mpi_get_const (int no); /* 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_snatch( w, u) gcry_mpi_snatch( (w), (u) ) #define mpi_set( w, u) gcry_mpi_set( (w), (u) ) #define mpi_set_ui( w, u) gcry_mpi_set_ui( (w), (u) ) #define mpi_abs( w ) gcry_mpi_abs( (w) ) #define mpi_neg( w, u) gcry_mpi_neg( (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_is_neg( a ) gcry_mpi_is_neg ((a)) #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_point_new(n) gcry_mpi_point_new((n)) #define mpi_point_release(p) \ do \ { \ gcry_mpi_point_release ((p)); \ (p) = NULL; \ } \ while (0) #define mpi_point_get(x,y,z,p) gcry_mpi_point_get((x),(y),(z),(p)) #define mpi_point_snatch_get(x,y,z,p) gcry_mpi_point_snatch_get((x),(y),(z),(p)) #define mpi_point_set(p,x,y,z) gcry_mpi_point_set((p),(x),(y),(z)) #define mpi_point_snatch_set(p,x,y,z) gcry_mpi_point_snatch_set((p),(x),(y),(z)) #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, GCRY_CIPHER_SALSA20 = 313, GCRY_CIPHER_SALSA20R12 = 314, GCRY_CIPHER_GOST28147 = 315, GCRY_CIPHER_CHACHA20 = 316 }; /* 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. */ GCRY_CIPHER_MODE_AESWRAP = 7, /* AES-WRAP algorithm. */ GCRY_CIPHER_MODE_CCM = 8, /* Counter with CBC-MAC. */ GCRY_CIPHER_MODE_GCM = 9, /* Galois Counter Mode. */ GCRY_CIPHER_MODE_POLY1305 = 10, /* Poly1305 based AEAD mode. */ GCRY_CIPHER_MODE_OCB = 11, /* OCB3 mode. */ GCRY_CIPHER_MODE_CFB8 = 12, /* Cipher feedback (8 bit mode). */ GCRY_CIPHER_MODE_XTS = 13 /* XTS mode. */ }; /* 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). */ }; /* GCM works only with blocks of 128 bits */ #define GCRY_GCM_BLOCK_LEN (128 / 8) /* CCM works only with blocks of 128 bits. */ #define GCRY_CCM_BLOCK_LEN (128 / 8) /* OCB works only with blocks of 128 bits. */ #define GCRY_OCB_BLOCK_LEN (128 / 8) /* XTS works only with blocks of 128 bits. */ #define GCRY_XTS_BLOCK_LEN (128 / 8) /* 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 cipher 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 bytes 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); /* Provide additional authentication data for AEAD modes/ciphers. */ gcry_error_t gcry_cipher_authenticate (gcry_cipher_hd_t hd, const void *abuf, size_t abuflen); /* Get authentication tag for AEAD modes/ciphers. */ gcry_error_t gcry_cipher_gettag (gcry_cipher_hd_t hd, void *outtag, size_t taglen); /* Check authentication tag for AEAD modes/ciphers. */ gcry_error_t gcry_cipher_checktag (gcry_cipher_hd_t hd, const void *intag, size_t taglen); /* 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 ) #define gcry_cipher_set_sbox(h,oid) gcry_cipher_ctl( (h), GCRYCTL_SET_SBOX, \ (void *) oid, 0); /* Indicate to the encrypt and decrypt functions that the next call provides the final data. Only used with some modes. */ #define gcry_cipher_final(a) \ gcry_cipher_ctl ((a), GCRYCTL_FINALIZE, NULL, 0) /* 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); /* Retrieve the key length in bytes used with algorithm A. */ size_t gcry_cipher_get_algo_keylen (int algo); /* Retrieve the block length in bytes 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 ) /************************************ * * * Asymmetric Cipher Functions * * * ************************************/ /* The algorithms and their IDs we support. */ enum gcry_pk_algos { GCRY_PK_RSA = 1, /* RSA */ GCRY_PK_RSA_E = 2, /* (deprecated: use 1). */ GCRY_PK_RSA_S = 3, /* (deprecated: use 1). */ GCRY_PK_ELG_E = 16, /* (deprecated: use 20). */ GCRY_PK_DSA = 17, /* Digital Signature Algorithm. */ GCRY_PK_ECC = 18, /* Generic ECC. */ GCRY_PK_ELG = 20, /* Elgamal */ GCRY_PK_ECDSA = 301, /* (only for external use). */ GCRY_PK_ECDH = 302, /* (only for external use). */ GCRY_PK_EDDSA = 303 /* (only for external use). */ }; /* 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. */ /* Modes used with gcry_pubkey_get_sexp. */ #define GCRY_PK_GET_PUBKEY 1 #define GCRY_PK_GET_SECKEY 2 /* 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; /* Return the so called KEYGRIP which is the SHA-1 hash of the public key parameters expressed in a way depending on the algorithm. */ unsigned char *gcry_pk_get_keygrip (gcry_sexp_t key, unsigned char *array); /* Return the name of the curve matching KEY. */ const char *gcry_pk_get_curve (gcry_sexp_t key, int iterator, unsigned int *r_nbits); /* Return an S-expression with the parameters of the named ECC curve NAME. ALGO must be set to an ECC algorithm. */ gcry_sexp_t gcry_pk_get_param (int algo, const char *name); /* 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 ) /* Return an S-expression representing the context CTX. */ gcry_error_t gcry_pubkey_get_sexp (gcry_sexp_t *r_sexp, int mode, gcry_ctx_t ctx); /************************************ * * * Cryptograhic Hash Functions * * * ************************************/ /* Algorithm IDs for the hash functions we know about. Not all of them are implemented. */ 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 as used by gpg <= 1.3.2. */ 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, GCRY_MD_TIGER1 = 306, /* TIGER fixed. */ GCRY_MD_TIGER2 = 307, /* TIGER2 variant. */ GCRY_MD_GOSTR3411_94 = 308, /* GOST R 34.11-94. */ GCRY_MD_STRIBOG256 = 309, /* GOST R 34.11-2012, 256 bit. */ GCRY_MD_STRIBOG512 = 310, /* GOST R 34.11-2012, 512 bit. */ GCRY_MD_GOSTR3411_CP = 311, /* GOST R 34.11-94 with CryptoPro-A S-Box. */ GCRY_MD_SHA3_224 = 312, GCRY_MD_SHA3_256 = 313, GCRY_MD_SHA3_384 = 314, GCRY_MD_SHA3_512 = 315, GCRY_MD_SHAKE128 = 316, GCRY_MD_SHAKE256 = 317, GCRY_MD_BLAKE2B_512 = 318, GCRY_MD_BLAKE2B_384 = 319, GCRY_MD_BLAKE2B_256 = 320, GCRY_MD_BLAKE2B_160 = 321, GCRY_MD_BLAKE2S_256 = 322, GCRY_MD_BLAKE2S_224 = 323, GCRY_MD_BLAKE2S_160 = 324, GCRY_MD_BLAKE2S_128 = 325 }; /* 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. */ GCRY_MD_FLAG_BUGEMU1 = 0x0100 }; /* (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); /* Read more output from algorithm ALGO to BUFFER of size LENGTH from * digest object HD. Algorithm needs to be 'expendable-output function'. */ gpg_error_t gcry_md_extract (gcry_md_hd_t hd, int algo, void *buffer, size_t length); /* 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); /* Convenience function to hash multiple buffers. */ gpg_error_t gcry_md_hash_buffers (int algo, unsigned int flags, void *digest, const gcry_buffer_t *iov, int iovcnt); /* 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 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 bytes. */ 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-. 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)) /********************************************** * * * Message Authentication Code Functions * * * **********************************************/ /* The data object used to hold a handle to an encryption object. */ struct gcry_mac_handle; typedef struct gcry_mac_handle *gcry_mac_hd_t; /* Algorithm IDs for the hash functions we know about. Not all of them are implemented. */ enum gcry_mac_algos { GCRY_MAC_NONE = 0, GCRY_MAC_HMAC_SHA256 = 101, GCRY_MAC_HMAC_SHA224 = 102, GCRY_MAC_HMAC_SHA512 = 103, GCRY_MAC_HMAC_SHA384 = 104, GCRY_MAC_HMAC_SHA1 = 105, GCRY_MAC_HMAC_MD5 = 106, GCRY_MAC_HMAC_MD4 = 107, GCRY_MAC_HMAC_RMD160 = 108, GCRY_MAC_HMAC_TIGER1 = 109, /* The fixed TIGER variant */ GCRY_MAC_HMAC_WHIRLPOOL = 110, GCRY_MAC_HMAC_GOSTR3411_94 = 111, GCRY_MAC_HMAC_STRIBOG256 = 112, GCRY_MAC_HMAC_STRIBOG512 = 113, GCRY_MAC_HMAC_MD2 = 114, GCRY_MAC_HMAC_SHA3_224 = 115, GCRY_MAC_HMAC_SHA3_256 = 116, GCRY_MAC_HMAC_SHA3_384 = 117, GCRY_MAC_HMAC_SHA3_512 = 118, GCRY_MAC_CMAC_AES = 201, GCRY_MAC_CMAC_3DES = 202, GCRY_MAC_CMAC_CAMELLIA = 203, GCRY_MAC_CMAC_CAST5 = 204, GCRY_MAC_CMAC_BLOWFISH = 205, GCRY_MAC_CMAC_TWOFISH = 206, GCRY_MAC_CMAC_SERPENT = 207, GCRY_MAC_CMAC_SEED = 208, GCRY_MAC_CMAC_RFC2268 = 209, GCRY_MAC_CMAC_IDEA = 210, GCRY_MAC_CMAC_GOST28147 = 211, GCRY_MAC_GMAC_AES = 401, GCRY_MAC_GMAC_CAMELLIA = 402, GCRY_MAC_GMAC_TWOFISH = 403, GCRY_MAC_GMAC_SERPENT = 404, GCRY_MAC_GMAC_SEED = 405, GCRY_MAC_POLY1305 = 501, GCRY_MAC_POLY1305_AES = 502, GCRY_MAC_POLY1305_CAMELLIA = 503, GCRY_MAC_POLY1305_TWOFISH = 504, GCRY_MAC_POLY1305_SERPENT = 505, GCRY_MAC_POLY1305_SEED = 506 }; /* Flags used with the open function. */ enum gcry_mac_flags { GCRY_MAC_FLAG_SECURE = 1 /* Allocate all buffers in "secure" memory. */ }; /* Create a MAC handle for algorithm ALGO. FLAGS may be given as an bitwise OR of the gcry_mac_flags values. CTX maybe NULL or gcry_ctx_t object to be associated with HANDLE. */ gcry_error_t gcry_mac_open (gcry_mac_hd_t *handle, int algo, unsigned int flags, gcry_ctx_t ctx); /* Close the MAC handle H and release all resource. */ void gcry_mac_close (gcry_mac_hd_t h); /* Perform various operations on the MAC object H. */ gcry_error_t gcry_mac_ctl (gcry_mac_hd_t h, int cmd, void *buffer, size_t buflen); /* Retrieve various information about the MAC algorithm ALGO. */ gcry_error_t gcry_mac_algo_info (int algo, int what, void *buffer, size_t *nbytes); /* Set KEY of length KEYLEN bytes for the MAC handle HD. */ gcry_error_t gcry_mac_setkey (gcry_mac_hd_t hd, const void *key, size_t keylen); /* Set initialization vector IV of length IVLEN for the MAC handle HD. */ gcry_error_t gcry_mac_setiv (gcry_mac_hd_t hd, const void *iv, size_t ivlen); /* Pass LENGTH bytes of data in BUFFER to the MAC object HD so that it can update the MAC values. */ gcry_error_t gcry_mac_write (gcry_mac_hd_t hd, const void *buffer, size_t length); /* Read out the final authentication code from the MAC object HD to BUFFER. */ gcry_error_t gcry_mac_read (gcry_mac_hd_t hd, void *buffer, size_t *buflen); /* Verify the final authentication code from the MAC object HD with BUFFER. */ gcry_error_t gcry_mac_verify (gcry_mac_hd_t hd, const void *buffer, size_t buflen); /* Retrieve the algorithm used with MAC. */ int gcry_mac_get_algo (gcry_mac_hd_t hd); /* Retrieve the length in bytes of the MAC yielded by algorithm ALGO. */ unsigned int gcry_mac_get_algo_maclen (int algo); /* Retrieve the default key length in bytes used with algorithm A. */ unsigned int gcry_mac_get_algo_keylen (int algo); /* Map the MAC 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_mac_algo_name (int algorithm) _GCRY_GCC_ATTR_PURE; /* Map the algorithm name NAME to an MAC algorithm ID. Return 0 if the algorithm name is not known. */ int gcry_mac_map_name (const char *name) _GCRY_GCC_ATTR_PURE; /* Reset the handle to the state after open/setkey. */ #define gcry_mac_reset(h) gcry_mac_ctl ((h), GCRYCTL_RESET, NULL, 0) /* Return 0 if the algorithm A is available for use. */ #define gcry_mac_test_algo(a) \ gcry_mac_algo_info( (a), GCRYCTL_TEST_ALGO, NULL, NULL ) /****************************** * * * Key Derivation Functions * * * ******************************/ /* Algorithm IDs for the KDFs. */ enum gcry_kdf_algos { GCRY_KDF_NONE = 0, GCRY_KDF_SIMPLE_S2K = 16, GCRY_KDF_SALTED_S2K = 17, GCRY_KDF_ITERSALTED_S2K = 19, GCRY_KDF_PBKDF1 = 33, GCRY_KDF_PBKDF2 = 34, GCRY_KDF_SCRYPT = 48 }; /* Derive a key from a passphrase. */ gpg_error_t gcry_kdf_derive (const void *passphrase, size_t passphraselen, int algo, int subalgo, const void *salt, size_t saltlen, unsigned long iterations, size_t keysize, void *keybuffer); /************************************ * * * Random Generating Functions * * * ************************************/ /* The type of the random number generator. */ enum gcry_rng_types { GCRY_RNG_TYPE_STANDARD = 1, /* The default CSPRNG generator. */ GCRY_RNG_TYPE_FIPS = 2, /* The FIPS X9.31 AES generator. */ GCRY_RNG_TYPE_SYSTEM = 3 /* The system's native generator. */ }; /* 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 by using a level of GCRY_WEAK_RANDOM gcry_create_nonce is used 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 the 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. */ +/* Check whether the number X is prime. */ gcry_error_t gcry_prime_check (gcry_mpi_t x, unsigned int flags); /************************************ * * * Miscellaneous Stuff * * * ************************************/ /* Release the context object CTX. */ void gcry_ctx_release (gcry_ctx_t ctx); /* Log data using Libgcrypt's own log interface. */ void gcry_log_debug (const char *fmt, ...) _GCRY_GCC_ATTR_PRINTF(1,2); void gcry_log_debughex (const char *text, const void *buffer, size_t length); void gcry_log_debugmpi (const char *text, gcry_mpi_t mpi); void gcry_log_debugpnt (const char *text, gcry_mpi_point_t point, gcry_ctx_t ctx); void gcry_log_debugsxp (const char *text, gcry_sexp_t sexp); /* 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) #if 0 /* (Keep Emacsens' auto-indent happy.) */ { #endif #ifdef __cplusplus } #endif #endif /* _GCRYPT_H */ /* @emacs_local_vars_begin@ @emacs_local_vars_read_only@ @emacs_local_vars_end@ */ diff --git a/src/global.c b/src/global.c index 25815dd3..0796a945 100644 --- a/src/global.c +++ b/src/global.c @@ -1,1240 +1,1240 @@ /* global.c - global control functions * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 * 2004, 2005, 2006, 2008, 2011, * 2012 Free Software Foundation, Inc. * Copyright (C) 2013, 2014 g10 Code GmbH * * 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 . */ #include #include #include #include #include #include #include #include #include #ifdef HAVE_SYSLOG # include #endif /*HAVE_SYSLOG*/ #include "g10lib.h" #include "gcrypt-testapi.h" #include "cipher.h" #include "stdmem.h" /* our own memory allocator */ #include "secmem.h" /* our own secmem allocator */ /**************** * flag bits: 0 : general cipher debug * 1 : general MPI debug */ static unsigned int debug_flags; /* gcry_control (GCRYCTL_SET_FIPS_MODE), sets this flag so that the initialization code switched fips mode on. */ static int force_fips_mode; /* Controlled by global_init(). */ static int any_init_done; /* * Functions called before and after blocking syscalls. * Initialized by global_init and used via * _gcry_pre_syscall and _gcry_post_syscall. */ static void (*pre_syscall_func)(void); static void (*post_syscall_func)(void); /* Memory management. */ static gcry_handler_alloc_t alloc_func; static gcry_handler_alloc_t alloc_secure_func; static gcry_handler_secure_check_t is_secure_func; static gcry_handler_realloc_t realloc_func; static gcry_handler_free_t free_func; static gcry_handler_no_mem_t outofcore_handler; static void *outofcore_handler_value; static int no_secure_memory; /* Prototypes. */ static gpg_err_code_t external_lock_test (int cmd); /* This is our handmade constructor. It gets called by any function likely to be called at startup. The suggested way for an application to make sure that this has been called is by using gcry_check_version. */ static void global_init (void) { gcry_error_t err = 0; if (any_init_done) return; any_init_done = 1; /* Tell the random module that we have seen an init call. */ _gcry_set_preferred_rng_type (0); /* Get the system call clamp functions. */ if (!pre_syscall_func) gpgrt_get_syscall_clamp (&pre_syscall_func, &post_syscall_func); /* See whether the system is in FIPS mode. This needs to come as early as possible but after ATH has been initialized. */ _gcry_initialize_fips_mode (force_fips_mode); /* Before we do any other initialization we need to test available hardware features. */ _gcry_detect_hw_features (); /* Initialize the modules - this is mainly allocating some memory and creating mutexes. */ err = _gcry_cipher_init (); if (err) goto fail; err = _gcry_md_init (); if (err) goto fail; err = _gcry_mac_init (); if (err) goto fail; err = _gcry_pk_init (); if (err) goto fail; err = _gcry_primegen_init (); if (err) goto fail; err = _gcry_secmem_module_init (); if (err) goto fail; err = _gcry_mpi_init (); if (err) goto fail; return; fail: BUG (); } /* This function is called by the macro fips_is_operational and makes sure that the minimal initialization has been done. This is far from a perfect solution and hides problems with an improper initialization but at least in single-threaded mode it should work reliable. The reason we need this is that a lot of applications don't use Libgcrypt properly by not running any initialization code at all. They just call a Libgcrypt function and that is all what they want. Now with the FIPS mode, that has the side effect of entering FIPS mode (for security reasons, FIPS mode is the default if no initialization has been done) and bailing out immediately because the FSM is in the wrong state. If we always run the init code, Libgcrypt can test for FIPS mode and at least if not in FIPS mode, it will behave as before. Note that this on-the-fly initialization is only done for the cryptographic functions subject to FIPS mode and thus not all API calls will do such an initialization. */ int _gcry_global_is_operational (void) { if (!any_init_done) { #ifdef HAVE_SYSLOG syslog (LOG_USER|LOG_WARNING, "Libgcrypt warning: " "missing initialization - please fix the application"); #endif /*HAVE_SYSLOG*/ global_init (); } return _gcry_fips_is_operational (); } /* Version number parsing. */ /* This function parses the first portion of the version number S and stores it in *NUMBER. On success, this function returns a pointer into S starting with the first character, which is not part of the initial number portion; on failure, NULL is returned. */ static const char* parse_version_number( const char *s, int *number ) { int val = 0; if( *s == '0' && isdigit(s[1]) ) return NULL; /* leading zeros are not allowed */ for ( ; isdigit(*s); s++ ) { val *= 10; val += *s - '0'; } *number = val; return val < 0? NULL : s; } /* This function breaks up the complete string-representation of the version number S, which is of the following struture: ... The major, minor and micro number components will be stored in *MAJOR, *MINOR and *MICRO. On success, the last component, the patch level, will be returned; in failure, NULL will be returned. */ static const char * parse_version_string( const char *s, int *major, int *minor, int *micro ) { s = parse_version_number( s, major ); if( !s || *s != '.' ) return NULL; s++; s = parse_version_number( s, minor ); if( !s || *s != '.' ) return NULL; s++; s = parse_version_number( s, micro ); if( !s ) return NULL; return s; /* patchlevel */ } /* If REQ_VERSION is non-NULL, check that the version of the library is at minimum the requested one. Returns the string representation of the library version if the condition is satisfied; return NULL if the requested version is newer than that of the library. If a NULL is passed to this function, no check is done, but the string representation of the library is simply returned. */ const char * _gcry_check_version (const char *req_version) { const char *ver = VERSION; int my_major, my_minor, my_micro; int rq_major, rq_minor, rq_micro; const char *my_plvl; if (req_version && req_version[0] == 1 && req_version[1] == 1) return _gcry_compat_identification (); /* Initialize library. */ global_init (); if ( !req_version ) /* Caller wants our version number. */ return ver; /* Parse own version number. */ my_plvl = parse_version_string( ver, &my_major, &my_minor, &my_micro ); if ( !my_plvl ) /* very strange our own version is bogus. Shouldn't we use assert() here and bail out in case this happens? -mo. */ return NULL; /* Parse requested version number. */ if (!parse_version_string (req_version, &rq_major, &rq_minor, &rq_micro)) return NULL; /* req version string is invalid, this can happen. */ /* Compare version numbers. */ if ( my_major > rq_major || (my_major == rq_major && my_minor > rq_minor) || (my_major == rq_major && my_minor == rq_minor && my_micro > rq_micro) || (my_major == rq_major && my_minor == rq_minor && my_micro == rq_micro)) { return ver; } return NULL; } static void print_config ( int (*fnc)(FILE *fp, const char *format, ...), FILE *fp) { unsigned int hwfeatures, afeature; int i; const char *s; fnc (fp, "version:%s:%x:%s:%x:\n", VERSION, GCRYPT_VERSION_NUMBER, GPGRT_VERSION, GPGRT_VERSION_NUMBER); fnc (fp, "cc:%d:%s:\n", #if GPGRT_VERSION_NUMBER >= 0x011b00 /* 1.27 */ GPGRT_GCC_VERSION #else _GPG_ERR_GCC_VERSION /* Due to a bug in gpg-error.h. */ #endif , #ifdef __clang__ "clang:" __VERSION__ #elif __GNUC__ "gcc:" __VERSION__ #else ":" #endif ); fnc (fp, "ciphers:%s:\n", LIBGCRYPT_CIPHERS); fnc (fp, "pubkeys:%s:\n", LIBGCRYPT_PUBKEY_CIPHERS); fnc (fp, "digests:%s:\n", LIBGCRYPT_DIGESTS); fnc (fp, "rnd-mod:" #if USE_RNDEGD "egd:" #endif #if USE_RNDLINUX "linux:" #endif #if USE_RNDUNIX "unix:" #endif #if USE_RNDW32 "w32:" #endif "\n"); fnc (fp, "cpu-arch:" #if defined(HAVE_CPU_ARCH_X86) "x86" #elif defined(HAVE_CPU_ARCH_ALPHA) "alpha" #elif defined(HAVE_CPU_ARCH_SPARC) "sparc" #elif defined(HAVE_CPU_ARCH_MIPS) "mips" #elif defined(HAVE_CPU_ARCH_M68K) "m68k" #elif defined(HAVE_CPU_ARCH_PPC) "ppc" #elif defined(HAVE_CPU_ARCH_ARM) "arm" #endif ":\n"); fnc (fp, "mpi-asm:%s:\n", _gcry_mpi_get_hw_config ()); hwfeatures = _gcry_get_hw_features (); fnc (fp, "hwflist:"); for (i=0; (s = _gcry_enum_hw_features (i, &afeature)); i++) if ((hwfeatures & afeature)) fnc (fp, "%s:", s); fnc (fp, "\n"); /* We use y/n instead of 1/0 for the simple reason that Emacsen's compile error parser would accidentally flag that line when printed during "make check" as an error. */ fnc (fp, "fips-mode:%c:%c:\n", fips_mode ()? 'y':'n', _gcry_enforced_fips_mode ()? 'y':'n' ); /* The currently used RNG type. */ { i = _gcry_get_rng_type (0); switch (i) { case GCRY_RNG_TYPE_STANDARD: s = "standard"; break; case GCRY_RNG_TYPE_FIPS: s = "fips"; break; case GCRY_RNG_TYPE_SYSTEM: s = "system"; break; default: BUG (); } fnc (fp, "rng-type:%s:%d:\n", s, i); } } /* Command dispatcher function, acting as general control function. */ gcry_err_code_t _gcry_vcontrol (enum gcry_ctl_cmds cmd, va_list arg_ptr) { static int init_finished = 0; gcry_err_code_t rc = 0; switch (cmd) { case GCRYCTL_ENABLE_M_GUARD: _gcry_private_enable_m_guard (); break; case GCRYCTL_ENABLE_QUICK_RANDOM: _gcry_set_preferred_rng_type (0); _gcry_enable_quick_random_gen (); break; case GCRYCTL_FAKED_RANDOM_P: /* Return an error if the RNG is faked one (e.g. enabled by ENABLE_QUICK_RANDOM. */ if (_gcry_random_is_faked ()) rc = GPG_ERR_GENERAL; /* Use as TRUE value. */ break; case GCRYCTL_DUMP_RANDOM_STATS: _gcry_random_dump_stats (); break; case GCRYCTL_DUMP_MEMORY_STATS: /*m_print_stats("[fixme: prefix]");*/ break; case GCRYCTL_DUMP_SECMEM_STATS: _gcry_secmem_dump_stats (0); break; case GCRYCTL_DROP_PRIVS: global_init (); _gcry_secmem_init (0); break; case GCRYCTL_DISABLE_SECMEM: global_init (); no_secure_memory = 1; break; case GCRYCTL_INIT_SECMEM: global_init (); _gcry_secmem_init (va_arg (arg_ptr, unsigned int)); if ((_gcry_secmem_get_flags () & GCRY_SECMEM_FLAG_NOT_LOCKED)) rc = GPG_ERR_GENERAL; break; case GCRYCTL_TERM_SECMEM: global_init (); _gcry_secmem_term (); break; case GCRYCTL_DISABLE_SECMEM_WARN: _gcry_set_preferred_rng_type (0); _gcry_secmem_set_flags ((_gcry_secmem_get_flags () | GCRY_SECMEM_FLAG_NO_WARNING)); break; case GCRYCTL_SUSPEND_SECMEM_WARN: _gcry_set_preferred_rng_type (0); _gcry_secmem_set_flags ((_gcry_secmem_get_flags () | GCRY_SECMEM_FLAG_SUSPEND_WARNING)); break; case GCRYCTL_RESUME_SECMEM_WARN: _gcry_set_preferred_rng_type (0); _gcry_secmem_set_flags ((_gcry_secmem_get_flags () & ~GCRY_SECMEM_FLAG_SUSPEND_WARNING)); break; case GCRYCTL_USE_SECURE_RNDPOOL: global_init (); _gcry_secure_random_alloc (); /* Put random number into secure memory. */ break; case GCRYCTL_SET_RANDOM_SEED_FILE: _gcry_set_preferred_rng_type (0); _gcry_set_random_seed_file (va_arg (arg_ptr, const char *)); break; case GCRYCTL_UPDATE_RANDOM_SEED_FILE: _gcry_set_preferred_rng_type (0); if ( fips_is_operational () ) _gcry_update_random_seed_file (); break; case GCRYCTL_SET_VERBOSITY: _gcry_set_preferred_rng_type (0); _gcry_set_log_verbosity (va_arg (arg_ptr, int)); break; case GCRYCTL_SET_DEBUG_FLAGS: debug_flags |= va_arg (arg_ptr, unsigned int); break; case GCRYCTL_CLEAR_DEBUG_FLAGS: debug_flags &= ~va_arg (arg_ptr, unsigned int); break; case GCRYCTL_DISABLE_INTERNAL_LOCKING: /* Not used anymore. */ global_init (); break; case GCRYCTL_ANY_INITIALIZATION_P: if (any_init_done) rc = GPG_ERR_GENERAL; break; case GCRYCTL_INITIALIZATION_FINISHED_P: if (init_finished) rc = GPG_ERR_GENERAL; /* Yes. */ break; case GCRYCTL_INITIALIZATION_FINISHED: /* This is a hook which should be used by an application after all initialization has been done and right before any threads are started. It is not really needed but the only way to be really sure that all initialization for thread-safety has been done. */ if (! init_finished) { global_init (); /* Do only a basic random initialization, i.e. init the mutexes. */ _gcry_random_initialize (0); init_finished = 1; /* Force us into operational state if in FIPS mode. */ (void)fips_is_operational (); } break; case GCRYCTL_SET_THREAD_CBS: /* This is now a dummy call. We used to install our own thread library here. */ _gcry_set_preferred_rng_type (0); global_init (); break; case GCRYCTL_FAST_POLL: _gcry_set_preferred_rng_type (0); /* We need to do make sure that the random pool is really initialized so that the poll function is not a NOP. */ _gcry_random_initialize (1); if ( fips_is_operational () ) _gcry_fast_random_poll (); break; case GCRYCTL_SET_RNDEGD_SOCKET: #if USE_RNDEGD _gcry_set_preferred_rng_type (0); rc = _gcry_rndegd_set_socket_name (va_arg (arg_ptr, const char *)); #else rc = GPG_ERR_NOT_SUPPORTED; #endif break; case GCRYCTL_SET_RANDOM_DAEMON_SOCKET: _gcry_set_preferred_rng_type (0); _gcry_set_random_daemon_socket (va_arg (arg_ptr, const char *)); break; case GCRYCTL_USE_RANDOM_DAEMON: /* We need to do make sure that the random pool is really initialized so that the poll function is not a NOP. */ _gcry_set_preferred_rng_type (0); _gcry_random_initialize (1); _gcry_use_random_daemon (!! va_arg (arg_ptr, int)); break; case GCRYCTL_CLOSE_RANDOM_DEVICE: _gcry_random_close_fds (); break; /* This command dumps information pertaining to the configuration of libgcrypt to the given stream. It may be used before the initialization has been finished but not before a gcry_version_check. */ case GCRYCTL_PRINT_CONFIG: { FILE *fp = va_arg (arg_ptr, FILE *); _gcry_set_preferred_rng_type (0); print_config (fp?fprintf:_gcry_log_info_with_dummy_fp, fp); } break; case GCRYCTL_OPERATIONAL_P: /* Returns true if the library is in an operational state. This is always true for non-fips mode. */ _gcry_set_preferred_rng_type (0); if (_gcry_fips_test_operational ()) rc = GPG_ERR_GENERAL; /* Used as TRUE value */ break; case GCRYCTL_FIPS_MODE_P: if (fips_mode () && !_gcry_is_fips_mode_inactive () && !no_secure_memory) rc = GPG_ERR_GENERAL; /* Used as TRUE value */ break; case GCRYCTL_FORCE_FIPS_MODE: /* Performing this command puts the library into fips mode. If the library has already been initialized into fips mode, a selftest is triggered. It is not possible to put the libraty into fips mode after having passed the initialization. */ _gcry_set_preferred_rng_type (0); if (!any_init_done) { - /* Not yet intialized at all. Set a flag so that we are put + /* Not yet initialized at all. Set a flag so that we are put into fips mode during initialization. */ force_fips_mode = 1; } else { /* Already initialized. If we are already operational we run a selftest. If not we use the is_operational call to force us into operational state if possible. */ if (_gcry_fips_test_error_or_operational ()) _gcry_fips_run_selftests (1); if (_gcry_fips_is_operational ()) rc = GPG_ERR_GENERAL; /* Used as TRUE value */ } break; case GCRYCTL_SELFTEST: /* Run a selftest. This works in fips mode as well as in standard mode. In contrast to the power-up tests, we use an extended version of the selftests. Returns 0 on success or an error code. */ global_init (); rc = _gcry_fips_run_selftests (1); break; #if _GCRY_GCC_VERSION >= 40600 # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wswitch" #endif case PRIV_CTL_INIT_EXTRNG_TEST: /* Init external random test. */ rc = GPG_ERR_NOT_SUPPORTED; break; case PRIV_CTL_RUN_EXTRNG_TEST: /* Run external DRBG test. */ { struct gcry_drbg_test_vector *test = va_arg (arg_ptr, struct gcry_drbg_test_vector *); unsigned char *buf = va_arg (arg_ptr, unsigned char *); if (buf) rc = _gcry_rngdrbg_cavs_test (test, buf); else rc = _gcry_rngdrbg_healthcheck_one (test); } break; case PRIV_CTL_DEINIT_EXTRNG_TEST: /* Deinit external random test. */ rc = GPG_ERR_NOT_SUPPORTED; break; case PRIV_CTL_EXTERNAL_LOCK_TEST: /* Run external lock test */ rc = external_lock_test (va_arg (arg_ptr, int)); break; case PRIV_CTL_DUMP_SECMEM_STATS: _gcry_secmem_dump_stats (1); break; #if _GCRY_GCC_VERSION >= 40600 # pragma GCC diagnostic pop #endif case GCRYCTL_DISABLE_HWF: { const char *name = va_arg (arg_ptr, const char *); rc = _gcry_disable_hw_feature (name); } break; case GCRYCTL_SET_ENFORCED_FIPS_FLAG: if (!any_init_done) { /* Not yet initialized at all. Set the enforced fips mode flag */ _gcry_set_preferred_rng_type (0); _gcry_set_enforced_fips_mode (); } else rc = GPG_ERR_GENERAL; break; case GCRYCTL_SET_PREFERRED_RNG_TYPE: /* This may be called before gcry_check_version. */ { int i = va_arg (arg_ptr, int); /* Note that we may not pass 0 to _gcry_set_preferred_rng_type. */ if (i > 0) _gcry_set_preferred_rng_type (i); } break; case GCRYCTL_GET_CURRENT_RNG_TYPE: { int *ip = va_arg (arg_ptr, int*); if (ip) *ip = _gcry_get_rng_type (!any_init_done); } break; case GCRYCTL_DISABLE_LOCKED_SECMEM: _gcry_set_preferred_rng_type (0); _gcry_secmem_set_flags ((_gcry_secmem_get_flags () | GCRY_SECMEM_FLAG_NO_MLOCK)); break; case GCRYCTL_DISABLE_PRIV_DROP: _gcry_set_preferred_rng_type (0); _gcry_secmem_set_flags ((_gcry_secmem_get_flags () | GCRY_SECMEM_FLAG_NO_PRIV_DROP)); break; case GCRYCTL_INACTIVATE_FIPS_FLAG: case GCRYCTL_REACTIVATE_FIPS_FLAG: rc = GPG_ERR_NOT_IMPLEMENTED; break; case GCRYCTL_DRBG_REINIT: { const char *flagstr = va_arg (arg_ptr, const char *); gcry_buffer_t *pers = va_arg (arg_ptr, gcry_buffer_t *); int npers = va_arg (arg_ptr, int); if (va_arg (arg_ptr, void *) || npers < 0) rc = GPG_ERR_INV_ARG; else if (_gcry_get_rng_type (!any_init_done) != GCRY_RNG_TYPE_FIPS) rc = GPG_ERR_NOT_SUPPORTED; else rc = _gcry_rngdrbg_reinit (flagstr, pers, npers); } break; case GCRYCTL_REINIT_SYSCALL_CLAMP: if (!pre_syscall_func) gpgrt_get_syscall_clamp (&pre_syscall_func, &post_syscall_func); break; default: _gcry_set_preferred_rng_type (0); rc = GPG_ERR_INV_OP; } return rc; } /* Set custom allocation handlers. This is in general not useful * because the libgcrypt allocation functions are guaranteed to * provide proper allocation handlers which zeroize memory if needed. * NOTE: All 5 functions should be set. */ void _gcry_set_allocation_handler (gcry_handler_alloc_t new_alloc_func, gcry_handler_alloc_t new_alloc_secure_func, gcry_handler_secure_check_t new_is_secure_func, gcry_handler_realloc_t new_realloc_func, gcry_handler_free_t new_free_func) { global_init (); if (fips_mode ()) { /* We do not want to enforce the fips mode, but merely set a flag so that the application may check whether it is still in fips mode. */ _gcry_inactivate_fips_mode ("custom allocation handler"); } alloc_func = new_alloc_func; alloc_secure_func = new_alloc_secure_func; is_secure_func = new_is_secure_func; realloc_func = new_realloc_func; free_func = new_free_func; } /**************** * Set an optional handler which is called in case the xmalloc functions * ran out of memory. This handler may do one of these things: * o free some memory and return true, so that the xmalloc function * tries again. * o Do whatever it like and return false, so that the xmalloc functions * use the default fatal error handler. * o Terminate the program and don't return. * * The handler function is called with 3 arguments: The opaque value set with * this function, the requested memory size, and a flag with these bits * currently defined: * bit 0 set = secure memory has been requested. */ void _gcry_set_outofcore_handler (int (*f)(void*, size_t, unsigned int), void *value) { global_init (); if (fips_mode () ) { log_info ("out of core handler ignored in FIPS mode\n"); return; } outofcore_handler = f; outofcore_handler_value = value; } /* Return the no_secure_memory flag. */ static int get_no_secure_memory (void) { if (!no_secure_memory) return 0; if (_gcry_enforced_fips_mode ()) { no_secure_memory = 0; return 0; } return no_secure_memory; } static gcry_err_code_t do_malloc (size_t n, unsigned int flags, void **mem) { gcry_err_code_t err = 0; void *m; if ((flags & GCRY_ALLOC_FLAG_SECURE) && !get_no_secure_memory ()) { if (alloc_secure_func) m = (*alloc_secure_func) (n); else m = _gcry_private_malloc_secure (n, !!(flags & GCRY_ALLOC_FLAG_XHINT)); } else { if (alloc_func) m = (*alloc_func) (n); else m = _gcry_private_malloc (n); } if (!m) { /* Make sure that ERRNO has been set in case a user supplied memory handler didn't it correctly. */ if (!errno) gpg_err_set_errno (ENOMEM); err = gpg_err_code_from_errno (errno); } else *mem = m; return err; } void * _gcry_malloc (size_t n) { void *mem = NULL; do_malloc (n, 0, &mem); return mem; } static void * _gcry_malloc_secure_core (size_t n, int xhint) { void *mem = NULL; do_malloc (n, (GCRY_ALLOC_FLAG_SECURE | (xhint? GCRY_ALLOC_FLAG_XHINT:0)), &mem); return mem; } void * _gcry_malloc_secure (size_t n) { return _gcry_malloc_secure_core (n, 0); } int _gcry_is_secure (const void *a) { if (get_no_secure_memory ()) return 0; if (is_secure_func) return is_secure_func (a) ; return _gcry_private_is_secure (a); } void _gcry_check_heap( const void *a ) { (void)a; /* FIXME: implement this*/ #if 0 if( some_handler ) some_handler(a) else _gcry_private_check_heap(a) #endif } static void * _gcry_realloc_core (void *a, size_t n, int xhint) { void *p; /* To avoid problems with non-standard realloc implementations and our own secmem_realloc, we divert to malloc and free here. */ if (!a) return _gcry_malloc (n); if (!n) { xfree (a); return NULL; } if (realloc_func) p = realloc_func (a, n); else p = _gcry_private_realloc (a, n, xhint); if (!p && !errno) gpg_err_set_errno (ENOMEM); return p; } void * _gcry_realloc (void *a, size_t n) { return _gcry_realloc_core (a, n, 0); } void _gcry_free (void *p) { int save_errno; if (!p) return; /* In case ERRNO is set we better save it so that the free machinery may not accidentally change ERRNO. We restore it only if it was already set to comply with the usual C semantic for ERRNO. */ save_errno = errno; if (free_func) free_func (p); else _gcry_private_free (p); if (save_errno) gpg_err_set_errno (save_errno); } void * _gcry_calloc (size_t n, size_t m) { size_t bytes; void *p; bytes = n * m; /* size_t is unsigned so the behavior on overflow is defined. */ if (m && bytes / m != n) { gpg_err_set_errno (ENOMEM); return NULL; } p = _gcry_malloc (bytes); if (p) memset (p, 0, bytes); return p; } void * _gcry_calloc_secure (size_t n, size_t m) { size_t bytes; void *p; bytes = n * m; /* size_t is unsigned so the behavior on overflow is defined. */ if (m && bytes / m != n) { gpg_err_set_errno (ENOMEM); return NULL; } p = _gcry_malloc_secure (bytes); if (p) memset (p, 0, bytes); return p; } static char * _gcry_strdup_core (const char *string, int xhint) { char *string_cp = NULL; size_t string_n = 0; string_n = strlen (string); if (_gcry_is_secure (string)) string_cp = _gcry_malloc_secure_core (string_n + 1, xhint); else string_cp = _gcry_malloc (string_n + 1); if (string_cp) strcpy (string_cp, string); return string_cp; } /* Create and return a copy of the null-terminated string STRING. If * it is contained in secure memory, the copy will be contained in * secure memory as well. In an out-of-memory condition, NULL is * returned. */ char * _gcry_strdup (const char *string) { return _gcry_strdup_core (string, 0); } void * _gcry_xmalloc( size_t n ) { void *p; while ( !(p = _gcry_malloc( n )) ) { if ( fips_mode () || !outofcore_handler || !outofcore_handler (outofcore_handler_value, n, 0) ) { _gcry_fatal_error (gpg_err_code_from_errno (errno), NULL); } } return p; } void * _gcry_xrealloc( void *a, size_t n ) { void *p; while (!(p = _gcry_realloc_core (a, n, 1))) { if ( fips_mode () || !outofcore_handler || !outofcore_handler (outofcore_handler_value, n, _gcry_is_secure(a)? 3:2)) { _gcry_fatal_error (gpg_err_code_from_errno (errno), NULL ); } } return p; } void * _gcry_xmalloc_secure( size_t n ) { void *p; while (!(p = _gcry_malloc_secure_core (n, 1))) { if ( fips_mode () || !outofcore_handler || !outofcore_handler (outofcore_handler_value, n, 1) ) { _gcry_fatal_error (gpg_err_code_from_errno (errno), _("out of core in secure memory")); } } return p; } void * _gcry_xcalloc( size_t n, size_t m ) { size_t nbytes; void *p; nbytes = n * m; if (m && nbytes / m != n) { gpg_err_set_errno (ENOMEM); _gcry_fatal_error(gpg_err_code_from_errno (errno), NULL ); } p = _gcry_xmalloc ( nbytes ); memset ( p, 0, nbytes ); return p; } void * _gcry_xcalloc_secure( size_t n, size_t m ) { size_t nbytes; void *p; nbytes = n * m; if (m && nbytes / m != n) { gpg_err_set_errno (ENOMEM); _gcry_fatal_error(gpg_err_code_from_errno (errno), NULL ); } p = _gcry_xmalloc_secure ( nbytes ); memset ( p, 0, nbytes ); return p; } char * _gcry_xstrdup (const char *string) { char *p; while ( !(p = _gcry_strdup_core (string, 1)) ) { size_t n = strlen (string); int is_sec = !!_gcry_is_secure (string); if (fips_mode () || !outofcore_handler || !outofcore_handler (outofcore_handler_value, n, is_sec) ) { _gcry_fatal_error (gpg_err_code_from_errno (errno), is_sec? _("out of core in secure memory"):NULL); } } return p; } /* Used before blocking system calls. */ void _gcry_pre_syscall (void) { if (pre_syscall_func) pre_syscall_func (); } /* Used after blocking system calls. */ void _gcry_post_syscall (void) { if (post_syscall_func) post_syscall_func (); } int _gcry_get_debug_flag (unsigned int mask) { if ( fips_mode () ) return 0; return (debug_flags & mask); } /* It is often useful to get some feedback of long running operations. This function may be used to register a handler for this. The callback function CB is used as: void cb (void *opaque, const char *what, int printchar, int current, int total); Where WHAT is a string identifying the the type of the progress output, PRINTCHAR the character usually printed, CURRENT the amount of progress currently done and TOTAL the expected amount of progress. A value of 0 for TOTAL indicates that there is no estimation available. Defined values for WHAT: "need_entropy" X 0 number-of-bytes-required When running low on entropy "primegen" '\n' 0 0 Prime generated '!' Need to refresh the prime pool '<','>' Number of bits adjusted '^' Looking for a generator '.' Fermat tests on 10 candidates failed ':' Restart with a new random value '+' Rabin Miller test passed "pk_elg" '+','-','.','\n' 0 0 Only used in debugging mode. "pk_dsa" Only used in debugging mode. */ void _gcry_set_progress_handler (void (*cb)(void *,const char*,int, int, int), void *cb_data) { #if USE_DSA _gcry_register_pk_dsa_progress (cb, cb_data); #endif #if USE_ELGAMAL _gcry_register_pk_elg_progress (cb, cb_data); #endif _gcry_register_primegen_progress (cb, cb_data); _gcry_register_random_progress (cb, cb_data); } /* This is a helper for the regression test suite to test Libgcrypt's locks. It works using a one test lock with CMD controlling what to do: 30111 - Allocate and init lock 30112 - Take lock 30113 - Release lock 30114 - Destroy lock. This function is used by tests/t-lock.c - it is not part of the public API! */ static gpg_err_code_t external_lock_test (int cmd) { GPGRT_LOCK_DEFINE (testlock); gpg_err_code_t rc = 0; switch (cmd) { case 30111: /* Init Lock. */ rc = gpgrt_lock_init (&testlock); break; case 30112: /* Take Lock. */ rc = gpgrt_lock_lock (&testlock); break; case 30113: /* Release Lock. */ rc = gpgrt_lock_unlock (&testlock); break; case 30114: /* Destroy Lock. */ rc = gpgrt_lock_destroy (&testlock); break; default: rc = GPG_ERR_INV_OP; break; } return rc; } diff --git a/src/secmem.c b/src/secmem.c index 55424f21..8eb66307 100644 --- a/src/secmem.c +++ b/src/secmem.c @@ -1,878 +1,878 @@ /* secmem.c - memory allocation from a secure heap * Copyright (C) 1998, 1999, 2000, 2001, 2002, * 2003, 2007 Free Software Foundation, Inc. * Copyright (C) 2013, 2016 g10 Code GmbH * * 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 . */ #include #include #include #include #include #include #include #include #if defined(HAVE_MLOCK) || defined(HAVE_MMAP) #include #include #include #ifdef USE_CAPABILITIES #include #endif #endif #include "g10lib.h" #include "secmem.h" #if defined (MAP_ANON) && ! defined (MAP_ANONYMOUS) #define MAP_ANONYMOUS MAP_ANON #endif #define MINIMUM_POOL_SIZE 16384 #define STANDARD_POOL_SIZE 32768 #define DEFAULT_PAGE_SIZE 4096 typedef struct memblock { unsigned size; /* Size of the memory available to the user. */ int flags; /* See below. */ PROPERLY_ALIGNED_TYPE aligned; } memblock_t; /* This flag specifies that the memory block is in use. */ #define MB_FLAG_ACTIVE (1 << 0) /* An object describing a memory pool. */ typedef struct pooldesc_s { /* A link to the next pool. This is used to connect the overflow * pools. */ struct pooldesc_s *next; /* A memory buffer used as allocation pool. */ void *mem; /* The allocated size of MEM. */ size_t size; /* Flag indicating that this memory pool is ready for use. May be * checked in an atexit function. */ volatile int okay; /* Flag indicating whether MEM is mmapped. */ volatile int is_mmapped; /* The number of allocated bytes and the number of used blocks in * this pool. */ unsigned int cur_alloced, cur_blocks; } pooldesc_t; /* The pool of secure memory. This is the head of a linked list with * the first element being the standard mlock-ed pool and the * following elements being the overflow pools. */ static pooldesc_t mainpool; -/* A couple of flags whith some beeing set early. */ +/* A couple of flags whith some being set early. */ static int disable_secmem; static int show_warning; static int not_locked; static int no_warning; static int suspend_warning; static int no_mlock; static int no_priv_drop; /* Lock protecting accesses to the memory pools. */ GPGRT_LOCK_DEFINE (secmem_lock); /* Convenient macros. */ #define SECMEM_LOCK gpgrt_lock_lock (&secmem_lock) #define SECMEM_UNLOCK gpgrt_lock_unlock (&secmem_lock) /* The size of the memblock structure; this does not include the memory that is available to the user. */ #define BLOCK_HEAD_SIZE \ offsetof (memblock_t, aligned) /* Convert an address into the according memory block structure. */ #define ADDR_TO_BLOCK(addr) \ (memblock_t *) (void *) ((char *) addr - BLOCK_HEAD_SIZE) /* Check whether P points into POOL. */ static inline int ptr_into_pool_p (pooldesc_t *pool, const void *p) { /* We need to convert pointers to addresses. This is required by C-99 6.5.8 to avoid undefined behaviour. See also http://lists.gnupg.org/pipermail/gcrypt-devel/2007-February/001102.html */ uintptr_t p_addr = (uintptr_t)p; uintptr_t pool_addr = (uintptr_t)pool->mem; return p_addr >= pool_addr && p_addr < pool_addr + pool->size; } /* Update the stats. */ static void stats_update (pooldesc_t *pool, size_t add, size_t sub) { if (add) { pool->cur_alloced += add; pool->cur_blocks++; } if (sub) { pool->cur_alloced -= sub; pool->cur_blocks--; } } /* Return the block following MB or NULL, if MB is the last block. */ static memblock_t * mb_get_next (pooldesc_t *pool, memblock_t *mb) { memblock_t *mb_next; mb_next = (memblock_t *) (void *) ((char *) mb + BLOCK_HEAD_SIZE + mb->size); if (! ptr_into_pool_p (pool, mb_next)) mb_next = NULL; return mb_next; } /* Return the block preceding MB or NULL, if MB is the first block. */ static memblock_t * mb_get_prev (pooldesc_t *pool, memblock_t *mb) { memblock_t *mb_prev, *mb_next; if (mb == pool->mem) mb_prev = NULL; else { mb_prev = (memblock_t *) pool->mem; while (1) { mb_next = mb_get_next (pool, mb_prev); if (mb_next == mb) break; else mb_prev = mb_next; } } return mb_prev; } /* If the preceding block of MB and/or the following block of MB exist and are not active, merge them to form a bigger block. */ static void mb_merge (pooldesc_t *pool, memblock_t *mb) { memblock_t *mb_prev, *mb_next; mb_prev = mb_get_prev (pool, mb); mb_next = mb_get_next (pool, mb); if (mb_prev && (! (mb_prev->flags & MB_FLAG_ACTIVE))) { mb_prev->size += BLOCK_HEAD_SIZE + mb->size; mb = mb_prev; } if (mb_next && (! (mb_next->flags & MB_FLAG_ACTIVE))) mb->size += BLOCK_HEAD_SIZE + mb_next->size; } /* Return a new block, which can hold SIZE bytes. */ static memblock_t * mb_get_new (pooldesc_t *pool, memblock_t *block, size_t size) { memblock_t *mb, *mb_split; for (mb = block; ptr_into_pool_p (pool, mb); mb = mb_get_next (pool, mb)) if (! (mb->flags & MB_FLAG_ACTIVE) && mb->size >= size) { /* Found a free block. */ mb->flags |= MB_FLAG_ACTIVE; if (mb->size - size > BLOCK_HEAD_SIZE) { /* Split block. */ mb_split = (memblock_t *) (void *) (((char *) mb) + BLOCK_HEAD_SIZE + size); mb_split->size = mb->size - size - BLOCK_HEAD_SIZE; mb_split->flags = 0; mb->size = size; mb_merge (pool, mb_split); } break; } if (! ptr_into_pool_p (pool, mb)) { gpg_err_set_errno (ENOMEM); mb = NULL; } return mb; } /* Print a warning message. */ static void print_warn (void) { if (!no_warning) log_info (_("Warning: using insecure memory!\n")); } /* Lock the memory pages of pool P of size N into core and drop * privileges. */ static void lock_pool_pages (void *p, size_t n) { #if defined(USE_CAPABILITIES) && defined(HAVE_MLOCK) int err; { cap_t cap; if (!no_priv_drop) { cap = cap_from_text ("cap_ipc_lock+ep"); cap_set_proc (cap); cap_free (cap); } err = no_mlock? 0 : mlock (p, n); if (err && errno) err = errno; if (!no_priv_drop) { cap = cap_from_text ("cap_ipc_lock+p"); cap_set_proc (cap); cap_free(cap); } } if (err) { if (err != EPERM #ifdef EAGAIN /* BSD and also Linux may return EAGAIN */ && err != EAGAIN #endif #ifdef ENOSYS /* Some SCOs return this (function not implemented) */ && err != ENOSYS #endif #ifdef ENOMEM /* Linux might return this. */ && err != ENOMEM #endif ) log_error ("can't lock memory: %s\n", strerror (err)); show_warning = 1; not_locked = 1; } #elif defined(HAVE_MLOCK) uid_t uid; int err; uid = getuid (); #ifdef HAVE_BROKEN_MLOCK /* Under HP/UX mlock segfaults if called by non-root. Note, we have noch checked whether mlock does really work under AIX where we also detected a broken nlock. Note further, that using plock () is not a good idea under AIX. */ if (uid) { errno = EPERM; err = errno; } else { err = no_mlock? 0 : mlock (p, n); if (err && errno) err = errno; } #else /* !HAVE_BROKEN_MLOCK */ err = no_mlock? 0 : mlock (p, n); if (err && errno) err = errno; #endif /* !HAVE_BROKEN_MLOCK */ /* Test whether we are running setuid(0). */ if (uid && ! geteuid ()) { /* Yes, we are. */ if (!no_priv_drop) { /* Check that we really dropped the privs. * Note: setuid(0) should always fail */ if (setuid (uid) || getuid () != geteuid () || !setuid (0)) log_fatal ("failed to reset uid: %s\n", strerror (errno)); } } if (err) { if (err != EPERM #ifdef EAGAIN /* BSD and also Linux may return this. */ && err != EAGAIN #endif #ifdef ENOSYS /* Some SCOs return this (function not implemented). */ && err != ENOSYS #endif #ifdef ENOMEM /* Linux might return this. */ && err != ENOMEM #endif ) log_error ("can't lock memory: %s\n", strerror (err)); show_warning = 1; not_locked = 1; } #elif defined ( __QNX__ ) /* QNX does not page at all, so the whole secure memory stuff does * not make much sense. However it is still of use because it * wipes out the memory on a free(). * Therefore it is sufficient to suppress the warning. */ (void)p; (void)n; #elif defined (HAVE_DOSISH_SYSTEM) || defined (__CYGWIN__) /* It does not make sense to print such a warning, given the fact that * this whole Windows !@#$% and their user base are inherently insecure. */ (void)p; (void)n; #elif defined (__riscos__) /* No virtual memory on RISC OS, so no pages are swapped to disc, * besides we don't have mmap, so we don't use it! ;-) * But don't complain, as explained above. */ (void)p; (void)n; #else (void)p; (void)n; if (!no_mlock) log_info ("Please note that you don't have secure memory on this system\n"); #endif } /* Initialize POOL. */ static void init_pool (pooldesc_t *pool, size_t n) { memblock_t *mb; pool->size = n; if (disable_secmem) log_bug ("secure memory is disabled"); #if HAVE_MMAP { size_t pgsize; long int pgsize_val; # if defined(HAVE_SYSCONF) && defined(_SC_PAGESIZE) pgsize_val = sysconf (_SC_PAGESIZE); # elif defined(HAVE_GETPAGESIZE) pgsize_val = getpagesize (); # else pgsize_val = -1; # endif pgsize = (pgsize_val != -1 && pgsize_val > 0)? pgsize_val:DEFAULT_PAGE_SIZE; pool->size = (pool->size + pgsize - 1) & ~(pgsize - 1); # ifdef MAP_ANONYMOUS pool->mem = mmap (0, pool->size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); # else /* map /dev/zero instead */ { int fd; fd = open ("/dev/zero", O_RDWR); if (fd == -1) { log_error ("can't open /dev/zero: %s\n", strerror (errno)); pool->mem = (void *) -1; } else { pool->mem = mmap (0, pool->size, (PROT_READ | PROT_WRITE), MAP_PRIVATE, fd, 0); close (fd); } } # endif if (pool->mem == (void *) -1) log_info ("can't mmap pool of %u bytes: %s - using malloc\n", (unsigned) pool->size, strerror (errno)); else { pool->is_mmapped = 1; pool->okay = 1; } } #endif /*HAVE_MMAP*/ if (!pool->okay) { pool->mem = malloc (pool->size); if (!pool->mem) log_fatal ("can't allocate memory pool of %u bytes\n", (unsigned) pool->size); else pool->okay = 1; } /* Initialize first memory block. */ mb = (memblock_t *) pool->mem; mb->size = pool->size; mb->flags = 0; } void _gcry_secmem_set_flags (unsigned flags) { int was_susp; SECMEM_LOCK; was_susp = suspend_warning; no_warning = flags & GCRY_SECMEM_FLAG_NO_WARNING; suspend_warning = flags & GCRY_SECMEM_FLAG_SUSPEND_WARNING; no_mlock = flags & GCRY_SECMEM_FLAG_NO_MLOCK; no_priv_drop = flags & GCRY_SECMEM_FLAG_NO_PRIV_DROP; /* and now issue the warning if it is not longer suspended */ if (was_susp && !suspend_warning && show_warning) { show_warning = 0; print_warn (); } SECMEM_UNLOCK; } unsigned int _gcry_secmem_get_flags (void) { unsigned flags; SECMEM_LOCK; flags = no_warning ? GCRY_SECMEM_FLAG_NO_WARNING : 0; flags |= suspend_warning ? GCRY_SECMEM_FLAG_SUSPEND_WARNING : 0; flags |= not_locked ? GCRY_SECMEM_FLAG_NOT_LOCKED : 0; flags |= no_mlock ? GCRY_SECMEM_FLAG_NO_MLOCK : 0; flags |= no_priv_drop ? GCRY_SECMEM_FLAG_NO_PRIV_DROP : 0; SECMEM_UNLOCK; return flags; } /* This function initializes the main memory pool MAINPOOL. Itis * expected to be called with the secmem lock held. */ static void _gcry_secmem_init_internal (size_t n) { pooldesc_t *pool; pool = &mainpool; if (!n) { #ifdef USE_CAPABILITIES /* drop all capabilities */ if (!no_priv_drop) { cap_t cap; cap = cap_from_text ("all-eip"); cap_set_proc (cap); cap_free (cap); } #elif !defined(HAVE_DOSISH_SYSTEM) uid_t uid; disable_secmem = 1; uid = getuid (); if (uid != geteuid ()) { if (setuid (uid) || getuid () != geteuid () || !setuid (0)) log_fatal ("failed to drop setuid\n"); } #endif } else { if (n < MINIMUM_POOL_SIZE) n = MINIMUM_POOL_SIZE; if (! pool->okay) { init_pool (pool, n); lock_pool_pages (pool->mem, n); } else log_error ("Oops, secure memory pool already initialized\n"); } } /* Initialize the secure memory system. If running with the necessary privileges, the secure memory pool will be locked into the core in order to prevent page-outs of the data. Furthermore allocated secure memory will be wiped out when released. */ void _gcry_secmem_init (size_t n) { SECMEM_LOCK; _gcry_secmem_init_internal (n); SECMEM_UNLOCK; } gcry_err_code_t _gcry_secmem_module_init () { /* Not anymore needed. */ return 0; } static void * _gcry_secmem_malloc_internal (size_t size, int xhint) { pooldesc_t *pool; memblock_t *mb; pool = &mainpool; if (!pool->okay) { /* Try to initialize the pool if the user forgot about it. */ _gcry_secmem_init_internal (STANDARD_POOL_SIZE); if (!pool->okay) { log_info (_("operation is not possible without " "initialized secure memory\n")); gpg_err_set_errno (ENOMEM); return NULL; } } if (not_locked && fips_mode ()) { log_info (_("secure memory pool is not locked while in FIPS mode\n")); gpg_err_set_errno (ENOMEM); return NULL; } if (show_warning && !suspend_warning) { show_warning = 0; print_warn (); } /* Blocks are always a multiple of 32. */ size = ((size + 31) / 32) * 32; mb = mb_get_new (pool, (memblock_t *) pool->mem, size); if (mb) { stats_update (pool, size, 0); return &mb->aligned.c; } /* If we are called from xmalloc style function resort to the * overflow pools to return memory. We don't do this in FIPS mode, * though. */ if (xhint && !fips_mode ()) { for (pool = pool->next; pool; pool = pool->next) { mb = mb_get_new (pool, (memblock_t *) pool->mem, size); if (mb) { stats_update (pool, size, 0); return &mb->aligned.c; } } /* Allocate a new overflow pool. We put a new pool right after * the mainpool so that the next allocation will happen in that * pool and not in one of the older pools. When this new pool * gets full we will try to find space in the older pools. */ pool = calloc (1, sizeof *pool); if (!pool) return NULL; /* Not enough memory for a new pool descriptor. */ pool->size = STANDARD_POOL_SIZE; pool->mem = malloc (pool->size); if (!pool->mem) return NULL; /* Not enough memory available for a new pool. */ /* Initialize first memory block. */ mb = (memblock_t *) pool->mem; mb->size = pool->size; mb->flags = 0; pool->okay = 1; /* Take care: in _gcry_private_is_secure we do not lock and thus * we assume that the second assignment below is atomic. */ pool->next = mainpool.next; mainpool.next = pool; /* After the first time we allocated an overflow pool, print a * warning. */ if (!pool->next) print_warn (); /* Allocate. */ mb = mb_get_new (pool, (memblock_t *) pool->mem, size); if (mb) { stats_update (pool, size, 0); return &mb->aligned.c; } } return NULL; } /* Allocate a block from the secmem of SIZE. With XHINT set assume * that the caller is a xmalloc style function. */ void * _gcry_secmem_malloc (size_t size, int xhint) { void *p; SECMEM_LOCK; p = _gcry_secmem_malloc_internal (size, xhint); SECMEM_UNLOCK; return p; } static int _gcry_secmem_free_internal (void *a) { pooldesc_t *pool; memblock_t *mb; int size; for (pool = &mainpool; pool; pool = pool->next) if (pool->okay && ptr_into_pool_p (pool, a)) break; if (!pool) return 0; /* A does not belong to use. */ mb = ADDR_TO_BLOCK (a); size = mb->size; /* This does not make much sense: probably this memory is held in the * cache. We do it anyway: */ #define MB_WIPE_OUT(byte) \ wipememory2 (((char *) mb + BLOCK_HEAD_SIZE), (byte), size); MB_WIPE_OUT (0xff); MB_WIPE_OUT (0xaa); MB_WIPE_OUT (0x55); MB_WIPE_OUT (0x00); /* Update stats. */ stats_update (pool, 0, size); mb->flags &= ~MB_FLAG_ACTIVE; mb_merge (pool, mb); return 1; /* Freed. */ } /* Wipe out and release memory. Returns true if this function * actually released A. */ int _gcry_secmem_free (void *a) { int mine; if (!a) return 1; /* Tell caller that we handled it. */ SECMEM_LOCK; mine = _gcry_secmem_free_internal (a); SECMEM_UNLOCK; return mine; } static void * _gcry_secmem_realloc_internal (void *p, size_t newsize, int xhint) { memblock_t *mb; size_t size; void *a; mb = (memblock_t *) (void *) ((char *) p - ((size_t) &((memblock_t *) 0)->aligned.c)); size = mb->size; if (newsize < size) { /* It is easier to not shrink the memory. */ a = p; } else { a = _gcry_secmem_malloc_internal (newsize, xhint); if (a) { memcpy (a, p, size); memset ((char *) a + size, 0, newsize - size); _gcry_secmem_free_internal (p); } } return a; } /* Realloc memory. With XHINT set assume that the caller is a xmalloc * style function. */ void * _gcry_secmem_realloc (void *p, size_t newsize, int xhint) { void *a; SECMEM_LOCK; a = _gcry_secmem_realloc_internal (p, newsize, xhint); SECMEM_UNLOCK; return a; } /* Return true if P points into the secure memory areas. */ int _gcry_private_is_secure (const void *p) { pooldesc_t *pool; /* We do no lock here because once a pool is allocatred it will not * be removed anymore (except for gcry_secmem_term). Further, * adding a new pool to the list should be atomic. */ for (pool = &mainpool; pool; pool = pool->next) if (pool->okay && ptr_into_pool_p (pool, p)) return 1; return 0; } /**************** * Warning: This code might be called by an interrupt handler * and frankly, there should really be such a handler, * to make sure that the memory is wiped out. * We hope that the OS wipes out mlocked memory after * receiving a SIGKILL - it really should do so, otherwise * there is no chance to get the secure memory cleaned. */ void _gcry_secmem_term () { pooldesc_t *pool, *next; for (pool = &mainpool; pool; pool = next) { next = pool->next; if (!pool->okay) continue; wipememory2 (pool->mem, 0xff, pool->size); wipememory2 (pool->mem, 0xaa, pool->size); wipememory2 (pool->mem, 0x55, pool->size); wipememory2 (pool->mem, 0x00, pool->size); if (0) ; #if HAVE_MMAP else if (pool->is_mmapped) munmap (pool->mem, pool->size); #endif else free (pool->mem); pool->mem = NULL; pool->okay = 0; pool->size = 0; if (pool != &mainpool) free (pool); } mainpool.next = NULL; not_locked = 0; } /* Print stats of the secmem allocator. With EXTENDED passwed as true * a detiled listing is returned (used for testing). */ void _gcry_secmem_dump_stats (int extended) { pooldesc_t *pool; memblock_t *mb; int i, poolno; SECMEM_LOCK; for (pool = &mainpool, poolno = 0; pool; pool = pool->next, poolno++) { if (!extended) { if (pool->okay) log_info ("%-13s %u/%lu bytes in %u blocks\n", pool == &mainpool? "secmem usage:":"", pool->cur_alloced, (unsigned long)pool->size, pool->cur_blocks); } else { for (i = 0, mb = (memblock_t *) pool->mem; ptr_into_pool_p (pool, mb); mb = mb_get_next (pool, mb), i++) log_info ("SECMEM: pool %d %s block %i size %i\n", poolno, (mb->flags & MB_FLAG_ACTIVE) ? "used" : "free", i, mb->size); } } SECMEM_UNLOCK; } diff --git a/tests/basic.c b/tests/basic.c index 342bf73f..89b79173 100644 --- a/tests/basic.c +++ b/tests/basic.c @@ -1,10470 +1,10470 @@ /* basic.c - basic regression tests * Copyright (C) 2001, 2002, 2003, 2005, 2008, * 2009 Free Software Foundation, Inc. * Copyright (C) 2013 g10 Code GmbH * * 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 . */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include "../src/gcrypt-int.h" #define PGM "basic" #include "t-common.h" typedef struct test_spec_pubkey_key { const char *secret; const char *public; const char *grip; } test_spec_pubkey_key_t; typedef struct test_spec_pubkey { int id; int flags; test_spec_pubkey_key_t key; } test_spec_pubkey_t; #define FLAG_CRYPT (1 << 0) #define FLAG_SIGN (1 << 1) #define FLAG_GRIP (1 << 2) static int in_fips_mode; #define MAX_DATA_LEN 128 static void mismatch (const void *expected, size_t expectedlen, const void *computed, size_t computedlen) { const unsigned char *p; fprintf (stderr, "expected:"); for (p = expected; expectedlen; p++, expectedlen--) fprintf (stderr, " %02x", *p); fprintf (stderr, "\ncomputed:"); for (p = computed; computedlen; p++, computedlen--) fprintf (stderr, " %02x", *p); fprintf (stderr, "\n"); } /* 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 terminates on error. */ static void * hex2buffer (const char *string, size_t *r_length) { const char *s; unsigned char *buffer; size_t length; buffer = xmalloc (strlen(string)/2+1); length = 0; for (s=string; *s; s +=2 ) { if (!hexdigitp (s) || !hexdigitp (s+1)) die ("invalid hex digits in \"%s\"\n", string); ((unsigned char*)buffer)[length++] = xtoi_2 (s); } *r_length = length; return buffer; } static void show_sexp (const char *prefix, gcry_sexp_t a) { char *buf; size_t size; if (prefix) fputs (prefix, stderr); size = gcry_sexp_sprint (a, GCRYSEXP_FMT_ADVANCED, NULL, 0); buf = gcry_xmalloc (size); gcry_sexp_sprint (a, GCRYSEXP_FMT_ADVANCED, buf, size); fprintf (stderr, "%.*s", (int)size, buf); gcry_free (buf); } static void show_note (const char *format, ...) { va_list arg_ptr; if (!verbose && getenv ("srcdir")) fputs (" ", stderr); /* To align above "PASS: ". */ else fprintf (stderr, "%s: ", PGM); va_start (arg_ptr, format); vfprintf (stderr, format, arg_ptr); if (*format && format[strlen(format)-1] != '\n') putc ('\n', stderr); va_end (arg_ptr); } static void show_md_not_available (int algo) { static int list[100]; static int listlen; int i; if (!verbose && algo == GCRY_MD_MD2) return; /* Do not print the diagnostic for that one. */ for (i=0; i < listlen; i++) if (algo == list[i]) return; /* Note already printed. */ if (listlen < DIM (list)) list[listlen++] = algo; show_note ("hash algorithm %d not available - skipping tests", algo); } static void show_old_hmac_not_available (int algo) { static int list[100]; static int listlen; int i; if (!verbose && algo == GCRY_MD_MD2) return; /* Do not print the diagnostic for that one. */ for (i=0; i < listlen; i++) if (algo == list[i]) return; /* Note already printed. */ if (listlen < DIM (list)) list[listlen++] = algo; show_note ("hash algorithm %d for old HMAC API not available " "- skipping tests", algo); } static void show_mac_not_available (int algo) { static int list[100]; static int listlen; int i; if (!verbose && algo == GCRY_MD_MD2) return; /* Do not print the diagnostic for that one. */ for (i=0; i < listlen; i++) if (algo == list[i]) return; /* Note already printed. */ if (listlen < DIM (list)) list[listlen++] = algo; show_note ("MAC algorithm %d not available - skipping tests", algo); } void progress_handler (void *cb_data, const char *what, int printchar, int current, int total) { (void)cb_data; (void)what; (void)current; (void)total; if (printchar == '\n') fputs ( "", stdout); else putchar (printchar); fflush (stdout); } static void check_cbc_mac_cipher (void) { static const struct tv { int algo; char key[MAX_DATA_LEN]; unsigned char plaintext[MAX_DATA_LEN]; size_t plaintextlen; char mac[MAX_DATA_LEN]; } tv[] = { { GCRY_CIPHER_AES, "chicken teriyaki", "This is a sample plaintext for CBC MAC of sixtyfour bytes.......", 0, "\x23\x8f\x6d\xc7\x53\x6a\x62\x97\x11\xc4\xa5\x16\x43\xea\xb0\xb6" }, { GCRY_CIPHER_3DES, "abcdefghABCDEFGH01234567", "This is a sample plaintext for CBC MAC of sixtyfour bytes.......", 0, "\x5c\x11\xf0\x01\x47\xbd\x3d\x3a" }, { GCRY_CIPHER_DES, "abcdefgh", "This is a sample plaintext for CBC MAC of sixtyfour bytes.......", 0, "\xfa\x4b\xdf\x9d\xfa\xab\x01\x70" } }; gcry_cipher_hd_t hd; unsigned char out[MAX_DATA_LEN]; int i, blklen, keylen; gcry_error_t err = 0; if (verbose) fprintf (stderr, " Starting CBC MAC checks.\n"); for (i = 0; i < sizeof (tv) / sizeof (tv[0]); i++) { if (gcry_cipher_test_algo (tv[i].algo) && in_fips_mode) { if (verbose) fprintf (stderr, " algorithm %d not available in fips mode\n", tv[i].algo); continue; } err = gcry_cipher_open (&hd, tv[i].algo, GCRY_CIPHER_MODE_CBC, GCRY_CIPHER_CBC_MAC); if (!hd) { fail ("cbc-mac algo %d, gcry_cipher_open failed: %s\n", tv[i].algo, gpg_strerror (err)); return; } blklen = gcry_cipher_get_algo_blklen(tv[i].algo); if (!blklen) { fail ("cbc-mac algo %d, gcry_cipher_get_algo_blklen failed\n", tv[i].algo); gcry_cipher_close (hd); return; } keylen = gcry_cipher_get_algo_keylen (tv[i].algo); if (!keylen) { fail ("cbc-mac algo %d, gcry_cipher_get_algo_keylen failed\n", tv[i].algo); return; } err = gcry_cipher_setkey (hd, tv[i].key, keylen); if (err) { fail ("cbc-mac algo %d, gcry_cipher_setkey failed: %s\n", tv[i].algo, gpg_strerror (err)); gcry_cipher_close (hd); return; } err = gcry_cipher_setiv (hd, NULL, 0); if (err) { fail ("cbc-mac algo %d, gcry_cipher_setiv failed: %s\n", tv[i].algo, gpg_strerror (err)); gcry_cipher_close (hd); return; } if (verbose) fprintf (stderr, " checking CBC MAC for %s [%i]\n", gcry_cipher_algo_name (tv[i].algo), tv[i].algo); err = gcry_cipher_encrypt (hd, out, blklen, tv[i].plaintext, tv[i].plaintextlen ? tv[i].plaintextlen : strlen ((char*)tv[i].plaintext)); if (err) { fail ("cbc-mac algo %d, gcry_cipher_encrypt failed: %s\n", tv[i].algo, gpg_strerror (err)); gcry_cipher_close (hd); return; } #if 0 { int j; for (j = 0; j < gcry_cipher_get_algo_blklen (tv[i].algo); j++) printf ("\\x%02x", out[j] & 0xFF); printf ("\n"); } #endif if (memcmp (tv[i].mac, out, blklen)) fail ("cbc-mac algo %d, encrypt mismatch entry %d\n", tv[i].algo, i); gcry_cipher_close (hd); } if (verbose) fprintf (stderr, " Completed CBC MAC checks.\n"); } static void check_aes128_cbc_cts_cipher (void) { static const char key[128 / 8] = "chicken teriyaki"; static const unsigned char plaintext[] = "I would like the General Gau's Chicken, please, and wonton soup."; static const struct tv { unsigned char out[MAX_DATA_LEN]; int inlen; } tv[] = { { "\xc6\x35\x35\x68\xf2\xbf\x8c\xb4\xd8\xa5\x80\x36\x2d\xa7\xff\x7f" "\x97", 17 }, { "\xfc\x00\x78\x3e\x0e\xfd\xb2\xc1\xd4\x45\xd4\xc8\xef\xf7\xed\x22" "\x97\x68\x72\x68\xd6\xec\xcc\xc0\xc0\x7b\x25\xe2\x5e\xcf\xe5", 31 }, { "\x39\x31\x25\x23\xa7\x86\x62\xd5\xbe\x7f\xcb\xcc\x98\xeb\xf5\xa8" "\x97\x68\x72\x68\xd6\xec\xcc\xc0\xc0\x7b\x25\xe2\x5e\xcf\xe5\x84", 32 }, { "\x97\x68\x72\x68\xd6\xec\xcc\xc0\xc0\x7b\x25\xe2\x5e\xcf\xe5\x84" "\xb3\xff\xfd\x94\x0c\x16\xa1\x8c\x1b\x55\x49\xd2\xf8\x38\x02\x9e" "\x39\x31\x25\x23\xa7\x86\x62\xd5\xbe\x7f\xcb\xcc\x98\xeb\xf5", 47 }, { "\x97\x68\x72\x68\xd6\xec\xcc\xc0\xc0\x7b\x25\xe2\x5e\xcf\xe5\x84" "\x9d\xad\x8b\xbb\x96\xc4\xcd\xc0\x3b\xc1\x03\xe1\xa1\x94\xbb\xd8" "\x39\x31\x25\x23\xa7\x86\x62\xd5\xbe\x7f\xcb\xcc\x98\xeb\xf5\xa8", 48 }, { "\x97\x68\x72\x68\xd6\xec\xcc\xc0\xc0\x7b\x25\xe2\x5e\xcf\xe5\x84" "\x39\x31\x25\x23\xa7\x86\x62\xd5\xbe\x7f\xcb\xcc\x98\xeb\xf5\xa8" "\x48\x07\xef\xe8\x36\xee\x89\xa5\x26\x73\x0d\xbc\x2f\x7b\xc8\x40" "\x9d\xad\x8b\xbb\x96\xc4\xcd\xc0\x3b\xc1\x03\xe1\xa1\x94\xbb\xd8", 64 }, }; gcry_cipher_hd_t hd; unsigned char out[MAX_DATA_LEN]; int i; gcry_error_t err = 0; if (verbose) fprintf (stderr, " Starting AES128 CBC CTS checks.\n"); err = gcry_cipher_open (&hd, GCRY_CIPHER_AES, GCRY_CIPHER_MODE_CBC, GCRY_CIPHER_CBC_CTS); if (err) { fail ("aes-cbc-cts, gcry_cipher_open failed: %s\n", gpg_strerror (err)); return; } err = gcry_cipher_setkey (hd, key, 128 / 8); if (err) { fail ("aes-cbc-cts, gcry_cipher_setkey failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hd); return; } for (i = 0; i < sizeof (tv) / sizeof (tv[0]); i++) { err = gcry_cipher_setiv (hd, NULL, 0); if (err) { fail ("aes-cbc-cts, gcry_cipher_setiv failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hd); return; } if (verbose) fprintf (stderr, " checking encryption for length %i\n", tv[i].inlen); err = gcry_cipher_encrypt (hd, out, MAX_DATA_LEN, plaintext, tv[i].inlen); if (err) { fail ("aes-cbc-cts, gcry_cipher_encrypt failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hd); return; } if (memcmp (tv[i].out, out, tv[i].inlen)) fail ("aes-cbc-cts, encrypt mismatch entry %d\n", i); err = gcry_cipher_setiv (hd, NULL, 0); if (err) { fail ("aes-cbc-cts, gcry_cipher_setiv failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hd); return; } if (verbose) fprintf (stderr, " checking decryption for length %i\n", tv[i].inlen); err = gcry_cipher_decrypt (hd, out, tv[i].inlen, NULL, 0); if (err) { fail ("aes-cbc-cts, gcry_cipher_decrypt failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hd); return; } if (memcmp (plaintext, out, tv[i].inlen)) fail ("aes-cbc-cts, decrypt mismatch entry %d\n", i); } gcry_cipher_close (hd); if (verbose) fprintf (stderr, " Completed AES128 CBC CTS checks.\n"); } static void check_ctr_cipher (void) { static const struct tv { int algo; char key[MAX_DATA_LEN]; char ctr[MAX_DATA_LEN]; struct data { unsigned char plaintext[MAX_DATA_LEN]; int inlen; char out[MAX_DATA_LEN]; } data[8]; } tv[] = { /* http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf */ { GCRY_CIPHER_AES, "\x2b\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c", "\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff", { { "\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96\xe9\x3d\x7e\x11\x73\x93\x17\x2a", 16, "\x87\x4d\x61\x91\xb6\x20\xe3\x26\x1b\xef\x68\x64\x99\x0d\xb6\xce" }, { "\xae\x2d\x8a\x57\x1e\x03\xac\x9c\x9e\xb7\x6f\xac\x45\xaf\x8e\x51", 16, "\x98\x06\xf6\x6b\x79\x70\xfd\xff\x86\x17\x18\x7b\xb9\xff\xfd\xff" }, { "\x30\xc8\x1c\x46\xa3\x5c\xe4\x11\xe5\xfb\xc1\x19\x1a\x0a\x52\xef", 16, "\x5a\xe4\xdf\x3e\xdb\xd5\xd3\x5e\x5b\x4f\x09\x02\x0d\xb0\x3e\xab" }, { "\xf6\x9f\x24\x45\xdf\x4f\x9b\x17\xad\x2b\x41\x7b\xe6\x6c\x37\x10", 16, "\x1e\x03\x1d\xda\x2f\xbe\x03\xd1\x79\x21\x70\xa0\xf3\x00\x9c\xee" }, { "", 0, "" } } }, { GCRY_CIPHER_AES192, "\x8e\x73\xb0\xf7\xda\x0e\x64\x52\xc8\x10\xf3\x2b" "\x80\x90\x79\xe5\x62\xf8\xea\xd2\x52\x2c\x6b\x7b", "\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff", { { "\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96\xe9\x3d\x7e\x11\x73\x93\x17\x2a", 16, "\x1a\xbc\x93\x24\x17\x52\x1c\xa2\x4f\x2b\x04\x59\xfe\x7e\x6e\x0b" }, { "\xae\x2d\x8a\x57\x1e\x03\xac\x9c\x9e\xb7\x6f\xac\x45\xaf\x8e\x51", 16, "\x09\x03\x39\xec\x0a\xa6\xfa\xef\xd5\xcc\xc2\xc6\xf4\xce\x8e\x94" }, { "\x30\xc8\x1c\x46\xa3\x5c\xe4\x11\xe5\xfb\xc1\x19\x1a\x0a\x52\xef", 16, "\x1e\x36\xb2\x6b\xd1\xeb\xc6\x70\xd1\xbd\x1d\x66\x56\x20\xab\xf7" }, { "\xf6\x9f\x24\x45\xdf\x4f\x9b\x17\xad\x2b\x41\x7b\xe6\x6c\x37\x10", 16, "\x4f\x78\xa7\xf6\xd2\x98\x09\x58\x5a\x97\xda\xec\x58\xc6\xb0\x50" }, { "", 0, "" } } }, { GCRY_CIPHER_AES256, "\x60\x3d\xeb\x10\x15\xca\x71\xbe\x2b\x73\xae\xf0\x85\x7d\x77\x81" "\x1f\x35\x2c\x07\x3b\x61\x08\xd7\x2d\x98\x10\xa3\x09\x14\xdf\xf4", "\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff", { { "\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96\xe9\x3d\x7e\x11\x73\x93\x17\x2a", 16, "\x60\x1e\xc3\x13\x77\x57\x89\xa5\xb7\xa7\xf5\x04\xbb\xf3\xd2\x28" }, { "\xae\x2d\x8a\x57\x1e\x03\xac\x9c\x9e\xb7\x6f\xac\x45\xaf\x8e\x51", 16, "\xf4\x43\xe3\xca\x4d\x62\xb5\x9a\xca\x84\xe9\x90\xca\xca\xf5\xc5" }, { "\x30\xc8\x1c\x46\xa3\x5c\xe4\x11\xe5\xfb\xc1\x19\x1a\x0a\x52\xef", 16, "\x2b\x09\x30\xda\xa2\x3d\xe9\x4c\xe8\x70\x17\xba\x2d\x84\x98\x8d" }, { "\xf6\x9f\x24\x45\xdf\x4f\x9b\x17\xad\x2b\x41\x7b\xe6\x6c\x37\x10", 16, "\xdf\xc9\xc5\x8d\xb6\x7a\xad\xa6\x13\xc2\xdd\x08\x45\x79\x41\xa6" }, { "", 0, "" } } }, /* Some truncation tests. With a truncated second block and also with a single truncated block. */ { GCRY_CIPHER_AES, "\x2b\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c", "\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff", {{"\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96\xe9\x3d\x7e\x11\x73\x93\x17\x2a", 16, "\x87\x4d\x61\x91\xb6\x20\xe3\x26\x1b\xef\x68\x64\x99\x0d\xb6\xce" }, {"\xae\x2d\x8a\x57\x1e\x03\xac\x9c\x9e\xb7\x6f\xac\x45\xaf\x8e", 15, "\x98\x06\xf6\x6b\x79\x70\xfd\xff\x86\x17\x18\x7b\xb9\xff\xfd" }, {"", 0, "" } } }, { GCRY_CIPHER_AES, "\x2b\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c", "\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff", {{"\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96\xe9\x3d\x7e\x11\x73\x93\x17\x2a", 16, "\x87\x4d\x61\x91\xb6\x20\xe3\x26\x1b\xef\x68\x64\x99\x0d\xb6\xce" }, {"\xae", 1, "\x98" }, {"", 0, "" } } }, { GCRY_CIPHER_AES, "\x2b\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c", "\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff", {{"\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96\xe9\x3d\x7e\x11\x73\x93\x17", 15, "\x87\x4d\x61\x91\xb6\x20\xe3\x26\x1b\xef\x68\x64\x99\x0d\xb6" }, {"", 0, "" } } }, { GCRY_CIPHER_AES, "\x2b\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c", "\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff", {{"\x6b", 1, "\x87" }, {"", 0, "" } } }, /* Tests to see whether it works correctly as a stream cipher. */ { GCRY_CIPHER_AES, "\x2b\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c", "\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff", {{"\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96\xe9\x3d\x7e\x11\x73\x93\x17\x2a", 16, "\x87\x4d\x61\x91\xb6\x20\xe3\x26\x1b\xef\x68\x64\x99\x0d\xb6\xce" }, {"\xae\x2d\x8a\x57\x1e\x03\xac\x9c\x9e\xb7\x6f\xac\x45\xaf\x8e", 15, "\x98\x06\xf6\x6b\x79\x70\xfd\xff\x86\x17\x18\x7b\xb9\xff\xfd" }, {"\x51\x30\xc8\x1c\x46\xa3\x5c\xe4\x11\xe5\xfb\xc1\x19\x1a\x0a\x52\xef", 17, "\xff\x5a\xe4\xdf\x3e\xdb\xd5\xd3\x5e\x5b\x4f\x09\x02\x0d\xb0\x3e\xab" }, {"\xf6\x9f\x24\x45\xdf\x4f\x9b\x17\xad\x2b\x41\x7b\xe6\x6c\x37\x10", 16, "\x1e\x03\x1d\xda\x2f\xbe\x03\xd1\x79\x21\x70\xa0\xf3\x00\x9c\xee" }, { "", 0, "" } } }, { GCRY_CIPHER_AES, "\x2b\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c", "\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff", {{"\x6b", 1, "\x87" }, {"\xc1\xbe", 2, "\x4d\x61" }, {"\xe2\x2e\x40", 3, "\x91\xb6\x20" }, {"\x9f", 1, "\xe3" }, {"\x96\xe9\x3d\x7e\x11\x73\x93\x17\x2a", 9, "\x26\x1b\xef\x68\x64\x99\x0d\xb6\xce" }, {"\xae\x2d\x8a\x57\x1e\x03\xac\x9c\x9e\xb7\x6f\xac\x45\xaf\x8e", 15, "\x98\x06\xf6\x6b\x79\x70\xfd\xff\x86\x17\x18\x7b\xb9\xff\xfd" }, {"\x51\x30\xc8\x1c\x46\xa3\x5c\xe4\x11", 9, "\xff\x5a\xe4\xdf\x3e\xdb\xd5\xd3\x5e" }, { "", 0, "" } } }, #if USE_CAST5 /* A selfmade test vector using an 64 bit block cipher. */ { GCRY_CIPHER_CAST5, "\x2b\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c", "\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8", {{"\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96\xe9\x3d\x7e\x11\x73\x93\x17\x2a", 16, "\xe8\xa7\xac\x68\xca\xca\xa0\x20\x10\xcb\x1b\xcc\x79\x2c\xc4\x48" }, {"\xae\x2d\x8a\x57\x1e\x03\xac\x9c", 8, "\x16\xe8\x72\x77\xb0\x98\x29\x68" }, {"\x9e\xb7\x6f\xac\x45\xaf\x8e\x51", 8, "\x9a\xb3\xa8\x03\x3b\xb4\x14\xba" }, {"\xae\x2d\x8a\x57\x1e\x03\xac\x9c\xa1\x00", 10, "\x31\x5e\xd3\xfb\x1b\x8d\xd1\xf9\xb0\x83" }, { "", 0, "" } } }, #endif /*USE_CAST5*/ { 0, "", "", { {"", 0, "" } } } }; gcry_cipher_hd_t hde, hdd; unsigned char out[MAX_DATA_LEN]; int i, j, keylen, blklen; gcry_error_t err = 0; size_t taglen2; if (verbose) fprintf (stderr, " Starting CTR cipher checks.\n"); for (i = 0; i < sizeof (tv) / sizeof (tv[0]); i++) { if (!tv[i].algo) continue; if (gcry_cipher_test_algo (tv[i].algo) && in_fips_mode) { if (verbose) fprintf (stderr, " algorithm %d not available in fips mode\n", tv[i].algo); continue; } err = gcry_cipher_open (&hde, tv[i].algo, GCRY_CIPHER_MODE_CTR, 0); if (!err) err = gcry_cipher_open (&hdd, tv[i].algo, GCRY_CIPHER_MODE_CTR, 0); if (err) { fail ("aes-ctr, gcry_cipher_open failed: %s\n", gpg_strerror (err)); return; } keylen = gcry_cipher_get_algo_keylen(tv[i].algo); if (!keylen) { fail ("aes-ctr, gcry_cipher_get_algo_keylen failed\n"); return; } err = gcry_cipher_setkey (hde, tv[i].key, keylen); if (!err) err = gcry_cipher_setkey (hdd, tv[i].key, keylen); if (err) { fail ("aes-ctr, gcry_cipher_setkey failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } blklen = gcry_cipher_get_algo_blklen(tv[i].algo); if (!blklen) { fail ("aes-ctr, gcry_cipher_get_algo_blklen failed\n"); return; } err = gcry_cipher_setctr (hde, tv[i].ctr, blklen); if (!err) err = gcry_cipher_setctr (hdd, tv[i].ctr, blklen); if (err) { fail ("aes-ctr, gcry_cipher_setctr failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } err = gcry_cipher_info (hde, GCRYCTL_GET_TAGLEN, NULL, &taglen2); if (gpg_err_code (err) != GPG_ERR_INV_CIPHER_MODE) { fail ("aes-ctr, gcryctl_get_taglen failed to fail (tv %d): %s\n", i, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } if (verbose) fprintf (stderr, " checking CTR mode for %s [%i]\n", gcry_cipher_algo_name (tv[i].algo), tv[i].algo); for (j = 0; tv[i].data[j].inlen; j++) { err = gcry_cipher_encrypt (hde, out, MAX_DATA_LEN, tv[i].data[j].plaintext, tv[i].data[j].inlen == -1 ? strlen ((char*)tv[i].data[j].plaintext) : tv[i].data[j].inlen); if (err) { fail ("aes-ctr, gcry_cipher_encrypt (%d, %d) failed: %s\n", i, j, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } if (memcmp (tv[i].data[j].out, out, tv[i].data[j].inlen)) { fail ("aes-ctr, encrypt mismatch entry %d:%d\n", i, j); mismatch (tv[i].data[j].out, tv[i].data[j].inlen, out, tv[i].data[j].inlen); } err = gcry_cipher_decrypt (hdd, out, tv[i].data[j].inlen, NULL, 0); if (err) { fail ("aes-ctr, gcry_cipher_decrypt (%d, %d) failed: %s\n", i, j, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } if (memcmp (tv[i].data[j].plaintext, out, tv[i].data[j].inlen)) { fail ("aes-ctr, decrypt mismatch entry %d:%d\n", i, j); mismatch (tv[i].data[j].plaintext, tv[i].data[j].inlen, out, tv[i].data[j].inlen); } } /* Now check that we get valid return codes back for good and bad inputs. */ err = gcry_cipher_encrypt (hde, out, MAX_DATA_LEN, "1234567890123456", 16); if (err) fail ("aes-ctr, encryption failed for valid input"); err = gcry_cipher_encrypt (hde, out, 15, "1234567890123456", 16); if (gpg_err_code (err) != GPG_ERR_BUFFER_TOO_SHORT) fail ("aes-ctr, too short output buffer returned wrong error: %s\n", gpg_strerror (err)); err = gcry_cipher_encrypt (hde, out, 0, "1234567890123456", 16); if (gpg_err_code (err) != GPG_ERR_BUFFER_TOO_SHORT) fail ("aes-ctr, 0 length output buffer returned wrong error: %s\n", gpg_strerror (err)); err = gcry_cipher_encrypt (hde, out, 16, "1234567890123456", 16); if (err) fail ("aes-ctr, correct length output buffer returned error: %s\n", gpg_strerror (err)); /* Again, now for decryption. */ err = gcry_cipher_decrypt (hde, out, MAX_DATA_LEN, "1234567890123456", 16); if (err) fail ("aes-ctr, decryption failed for valid input"); err = gcry_cipher_decrypt (hde, out, 15, "1234567890123456", 16); if (gpg_err_code (err) != GPG_ERR_BUFFER_TOO_SHORT) fail ("aes-ctr, too short output buffer returned wrong error: %s\n", gpg_strerror (err)); err = gcry_cipher_decrypt (hde, out, 0, "1234567890123456", 16); if (gpg_err_code (err) != GPG_ERR_BUFFER_TOO_SHORT) fail ("aes-ctr, 0 length output buffer returned wrong error: %s\n", gpg_strerror (err)); err = gcry_cipher_decrypt (hde, out, 16, "1234567890123456", 16); if (err) fail ("aes-ctr, correct length output buffer returned error: %s\n", gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); } if (verbose) fprintf (stderr, " Completed CTR cipher checks.\n"); } static void check_cfb_cipher (void) { static const struct tv { int algo; int cfb8; char key[MAX_DATA_LEN]; char iv[MAX_DATA_LEN]; struct data { unsigned char plaintext[MAX_DATA_LEN]; int inlen; char out[MAX_DATA_LEN]; } data[MAX_DATA_LEN]; } tv[] = { /* http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf */ { GCRY_CIPHER_AES, 0, "\x2b\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c", "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f", { { "\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96\xe9\x3d\x7e\x11\x73\x93\x17\x2a", 16, "\x3b\x3f\xd9\x2e\xb7\x2d\xad\x20\x33\x34\x49\xf8\xe8\x3c\xfb\x4a" }, { "\xae\x2d\x8a\x57\x1e\x03\xac\x9c\x9e\xb7\x6f\xac\x45\xaf\x8e\x51", 16, "\xc8\xa6\x45\x37\xa0\xb3\xa9\x3f\xcd\xe3\xcd\xad\x9f\x1c\xe5\x8b"}, { "\x30\xc8\x1c\x46\xa3\x5c\xe4\x11\xe5\xfb\xc1\x19\x1a\x0a\x52\xef", 16, "\x26\x75\x1f\x67\xa3\xcb\xb1\x40\xb1\x80\x8c\xf1\x87\xa4\xf4\xdf" }, { "\xf6\x9f\x24\x45\xdf\x4f\x9b\x17\xad\x2b\x41\x7b\xe6\x6c\x37\x10", 16, "\xc0\x4b\x05\x35\x7c\x5d\x1c\x0e\xea\xc4\xc6\x6f\x9f\xf7\xf2\xe6" }, } }, { GCRY_CIPHER_AES192, 0, "\x8e\x73\xb0\xf7\xda\x0e\x64\x52\xc8\x10\xf3\x2b" "\x80\x90\x79\xe5\x62\xf8\xea\xd2\x52\x2c\x6b\x7b", "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f", { { "\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96\xe9\x3d\x7e\x11\x73\x93\x17\x2a", 16, "\xcd\xc8\x0d\x6f\xdd\xf1\x8c\xab\x34\xc2\x59\x09\xc9\x9a\x41\x74" }, { "\xae\x2d\x8a\x57\x1e\x03\xac\x9c\x9e\xb7\x6f\xac\x45\xaf\x8e\x51", 16, "\x67\xce\x7f\x7f\x81\x17\x36\x21\x96\x1a\x2b\x70\x17\x1d\x3d\x7a" }, { "\x30\xc8\x1c\x46\xa3\x5c\xe4\x11\xe5\xfb\xc1\x19\x1a\x0a\x52\xef", 16, "\x2e\x1e\x8a\x1d\xd5\x9b\x88\xb1\xc8\xe6\x0f\xed\x1e\xfa\xc4\xc9" }, { "\xf6\x9f\x24\x45\xdf\x4f\x9b\x17\xad\x2b\x41\x7b\xe6\x6c\x37\x10", 16, "\xc0\x5f\x9f\x9c\xa9\x83\x4f\xa0\x42\xae\x8f\xba\x58\x4b\x09\xff" }, } }, { GCRY_CIPHER_AES256, 0, "\x60\x3d\xeb\x10\x15\xca\x71\xbe\x2b\x73\xae\xf0\x85\x7d\x77\x81" "\x1f\x35\x2c\x07\x3b\x61\x08\xd7\x2d\x98\x10\xa3\x09\x14\xdf\xf4", "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f", { { "\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96\xe9\x3d\x7e\x11\x73\x93\x17\x2a", 16, "\xdc\x7e\x84\xbf\xda\x79\x16\x4b\x7e\xcd\x84\x86\x98\x5d\x38\x60" }, { "\xae\x2d\x8a\x57\x1e\x03\xac\x9c\x9e\xb7\x6f\xac\x45\xaf\x8e\x51", 16, "\x39\xff\xed\x14\x3b\x28\xb1\xc8\x32\x11\x3c\x63\x31\xe5\x40\x7b" }, { "\x30\xc8\x1c\x46\xa3\x5c\xe4\x11\xe5\xfb\xc1\x19\x1a\x0a\x52\xef", 16, "\xdf\x10\x13\x24\x15\xe5\x4b\x92\xa1\x3e\xd0\xa8\x26\x7a\xe2\xf9" }, { "\xf6\x9f\x24\x45\xdf\x4f\x9b\x17\xad\x2b\x41\x7b\xe6\x6c\x37\x10", 16, "\x75\xa3\x85\x74\x1a\xb9\xce\xf8\x20\x31\x62\x3d\x55\xb1\xe4\x71" } } }, { GCRY_CIPHER_AES, 1, "\x2b\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c", "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f", { { "\x6b", 1, "\x3b"}, { "\xc1", 1, "\x79"}, { "\xbe", 1, "\x42"}, { "\xe2", 1, "\x4c"}, } }, { GCRY_CIPHER_AES192, 1, "\x8e\x73\xb0\xf7\xda\x0e\x64\x52\xc8\x10\xf3\x2b\x80\x90\x79\xe5" "\x62\xf8\xea\xd2\x52\x2c\x6b\x7b", "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f", { { "\x6b", 1, "\xcd"}, { "\xc1", 1, "\xa2"}, { "\xbe", 1, "\x52"}, { "\xe2", 1, "\x1e"}, } }, { GCRY_CIPHER_AES256, 1, "\x60\x3d\xeb\x10\x15\xca\x71\xbe\x2b\x73\xae\xf0\x85\x7d\x77\x81" "\x1f\x35\x2c\x07\x3b\x61\x08\xd7\x2d\x98\x10\xa3\x09\x14\xdf\xf4", "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f", { { "\x6b", 1, "\xdc"}, { "\xc1", 1, "\x1f"}, { "\xbe", 1, "\x1a"}, { "\xe2", 1, "\x85"}, } }, { GCRY_CIPHER_AES, 1, "\x3a\x6f\x91\x59\x26\x3f\xa6\xce\xf2\xa0\x75\xca\xfa\xce\x58\x17", "\x0f\xc2\x36\x62\xb7\xdb\xf7\x38\x27\xf0\xc7\xde\x32\x1c\xa3\x6e", { { "\x87\xef\xeb\x8d\x55\x9e\xd3\x36\x77\x28", 10, "\x8e\x9c\x50\x42\x56\x14\xd5\x40\xce\x11"}, } }, { GCRY_CIPHER_AES192, 1, "\x53\x7e\x7b\xf6\x61\xfd\x40\x24\xa0\x24\x61\x3f\x15\xb1\x36\x90" "\xf7\xd0\xc8\x47\xc1\xe1\x89\x65", "\x3a\x81\xf9\xd9\xd3\xc1\x55\xb0\xca\xad\x5d\x73\x34\x94\x76\xfc", { { "\xd3\xd8\xb9\xb9\x84\xad\xc2\x42\x37\xee", 10, "\x38\x79\xfe\xa7\x2a\xc9\x99\x29\xe5\x3a"}, } }, { GCRY_CIPHER_AES256, 1, "\xeb\xbb\x45\x66\xb5\xe1\x82\xe0\xf0\x72\x46\x6b\x0b\x31\x1d\xf3" "\x8f\x91\x75\xbc\x02\x13\xa5\x53\x0b\xce\x2e\xc4\xd7\x4f\x40\x0d", "\x09\x56\xa4\x8e\x01\x00\x2c\x9e\x16\x37\x6d\x6e\x30\x8d\xba\xd1", { { "\xb0\xfe\x25\xac\x8d\x3d\x28\xa2\xf4\x71", 10, "\x63\x8c\x68\x23\xe7\x25\x6f\xb5\x62\x6e"}, } }, { GCRY_CIPHER_3DES, 1, "\xe3\x34\x7a\x6b\x0b\xc1\x15\x2c\x64\x2a\x25\xcb\xd3\xbc\x31\xab" "\xfb\xa1\x62\xa8\x1f\x19\x7c\x15", "\xb7\x40\xcc\x21\xe9\x25\xe3\xc8", { { "\xdb\xe9\x15\xfc\xb3\x3b\xca\x18\xef\x14", 10, "\xf4\x80\x1a\x8d\x03\x9d\xb4\xca\x8f\xf6"}, } }, { GCRY_CIPHER_3DES, 1, "\x7c\xa2\x89\x38\xba\x6b\xec\x1f\xfe\xc7\x8f\x7c\xd6\x97\x61\x94" "\x7c\xa2\x89\x38\xba\x6b\xec\x1f", "\x95\x38\x96\x58\x6e\x49\xd3\x8f", { { "\x2e\xa9\x56\xd4\xa2\x11\xdb\x68\x59\xb7", 10, "\xf2\x0e\x53\x66\x74\xa6\x6f\xa7\x38\x05"}, } }, }; gcry_cipher_hd_t hde, hdd; unsigned char out[MAX_DATA_LEN]; int i, j, keylen, blklen, mode; gcry_error_t err = 0; if (verbose) fprintf (stderr, " Starting CFB checks.\n"); for (i = 0; i < sizeof (tv) / sizeof (tv[0]); i++) { if (gcry_cipher_test_algo (tv[i].algo) && in_fips_mode) { if (verbose) fprintf (stderr, " algorithm %d not available in fips mode\n", tv[i].algo); continue; } mode = tv[i].cfb8? GCRY_CIPHER_MODE_CFB8 : GCRY_CIPHER_MODE_CFB; if (verbose) fprintf (stderr, " checking CFB mode for %s [%i]\n", gcry_cipher_algo_name (tv[i].algo), tv[i].algo); err = gcry_cipher_open (&hde, tv[i].algo, mode, 0); if (!err) err = gcry_cipher_open (&hdd, tv[i].algo, mode, 0); if (err) { fail ("aes-cfb, gcry_cipher_open failed: %s\n", gpg_strerror (err)); return; } keylen = gcry_cipher_get_algo_keylen(tv[i].algo); if (!keylen) { fail ("aes-cfb, gcry_cipher_get_algo_keylen failed\n"); return; } err = gcry_cipher_setkey (hde, tv[i].key, keylen); if (!err) err = gcry_cipher_setkey (hdd, tv[i].key, keylen); if (err) { fail ("aes-cfb, gcry_cipher_setkey failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } blklen = gcry_cipher_get_algo_blklen(tv[i].algo); if (!blklen) { fail ("aes-cfb, gcry_cipher_get_algo_blklen failed\n"); return; } err = gcry_cipher_setiv (hde, tv[i].iv, blklen); if (!err) err = gcry_cipher_setiv (hdd, tv[i].iv, blklen); if (err) { fail ("aes-cfb, gcry_cipher_setiv failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } for (j = 0; tv[i].data[j].inlen; j++) { err = gcry_cipher_encrypt (hde, out, MAX_DATA_LEN, tv[i].data[j].plaintext, tv[i].data[j].inlen); if (err) { fail ("aes-cfb, gcry_cipher_encrypt (%d, %d) failed: %s\n", i, j, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } if (memcmp (tv[i].data[j].out, out, tv[i].data[j].inlen)) { fail ("aes-cfb, encrypt mismatch entry %d:%d\n", i, j); } err = gcry_cipher_decrypt (hdd, out, tv[i].data[j].inlen, NULL, 0); if (err) { fail ("aes-cfb, gcry_cipher_decrypt (%d, %d) failed: %s\n", i, j, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } if (memcmp (tv[i].data[j].plaintext, out, tv[i].data[j].inlen)) fail ("aes-cfb, decrypt mismatch entry %d:%d\n", i, j); } gcry_cipher_close (hde); gcry_cipher_close (hdd); } if (verbose) fprintf (stderr, " Completed CFB checks.\n"); } static void check_ofb_cipher (void) { static const struct tv { int algo; char key[MAX_DATA_LEN]; char iv[MAX_DATA_LEN]; struct data { unsigned char plaintext[MAX_DATA_LEN]; int inlen; char out[MAX_DATA_LEN]; } data[MAX_DATA_LEN]; } tv[] = { /* http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf */ { GCRY_CIPHER_AES, "\x2b\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c", "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f", { { "\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96\xe9\x3d\x7e\x11\x73\x93\x17\x2a", 16, "\x3b\x3f\xd9\x2e\xb7\x2d\xad\x20\x33\x34\x49\xf8\xe8\x3c\xfb\x4a" }, { "\xae\x2d\x8a\x57\x1e\x03\xac\x9c\x9e\xb7\x6f\xac\x45\xaf\x8e\x51", 16, "\x77\x89\x50\x8d\x16\x91\x8f\x03\xf5\x3c\x52\xda\xc5\x4e\xd8\x25"}, { "\x30\xc8\x1c\x46\xa3\x5c\xe4\x11\xe5\xfb\xc1\x19\x1a\x0a\x52\xef", 16, "\x97\x40\x05\x1e\x9c\x5f\xec\xf6\x43\x44\xf7\xa8\x22\x60\xed\xcc" }, { "\xf6\x9f\x24\x45\xdf\x4f\x9b\x17\xad\x2b\x41\x7b\xe6\x6c\x37\x10", 16, "\x30\x4c\x65\x28\xf6\x59\xc7\x78\x66\xa5\x10\xd9\xc1\xd6\xae\x5e" }, } }, { GCRY_CIPHER_AES192, "\x8e\x73\xb0\xf7\xda\x0e\x64\x52\xc8\x10\xf3\x2b" "\x80\x90\x79\xe5\x62\xf8\xea\xd2\x52\x2c\x6b\x7b", "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f", { { "\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96\xe9\x3d\x7e\x11\x73\x93\x17\x2a", 16, "\xcd\xc8\x0d\x6f\xdd\xf1\x8c\xab\x34\xc2\x59\x09\xc9\x9a\x41\x74" }, { "\xae\x2d\x8a\x57\x1e\x03\xac\x9c\x9e\xb7\x6f\xac\x45\xaf\x8e\x51", 16, "\xfc\xc2\x8b\x8d\x4c\x63\x83\x7c\x09\xe8\x17\x00\xc1\x10\x04\x01" }, { "\x30\xc8\x1c\x46\xa3\x5c\xe4\x11\xe5\xfb\xc1\x19\x1a\x0a\x52\xef", 16, "\x8d\x9a\x9a\xea\xc0\xf6\x59\x6f\x55\x9c\x6d\x4d\xaf\x59\xa5\xf2" }, { "\xf6\x9f\x24\x45\xdf\x4f\x9b\x17\xad\x2b\x41\x7b\xe6\x6c\x37\x10", 16, "\x6d\x9f\x20\x08\x57\xca\x6c\x3e\x9c\xac\x52\x4b\xd9\xac\xc9\x2a" }, } }, { GCRY_CIPHER_AES256, "\x60\x3d\xeb\x10\x15\xca\x71\xbe\x2b\x73\xae\xf0\x85\x7d\x77\x81" "\x1f\x35\x2c\x07\x3b\x61\x08\xd7\x2d\x98\x10\xa3\x09\x14\xdf\xf4", "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f", { { "\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96\xe9\x3d\x7e\x11\x73\x93\x17\x2a", 16, "\xdc\x7e\x84\xbf\xda\x79\x16\x4b\x7e\xcd\x84\x86\x98\x5d\x38\x60" }, { "\xae\x2d\x8a\x57\x1e\x03\xac\x9c\x9e\xb7\x6f\xac\x45\xaf\x8e\x51", 16, "\x4f\xeb\xdc\x67\x40\xd2\x0b\x3a\xc8\x8f\x6a\xd8\x2a\x4f\xb0\x8d" }, { "\x30\xc8\x1c\x46\xa3\x5c\xe4\x11\xe5\xfb\xc1\x19\x1a\x0a\x52\xef", 16, "\x71\xab\x47\xa0\x86\xe8\x6e\xed\xf3\x9d\x1c\x5b\xba\x97\xc4\x08" }, { "\xf6\x9f\x24\x45\xdf\x4f\x9b\x17\xad\x2b\x41\x7b\xe6\x6c\x37\x10", 16, "\x01\x26\x14\x1d\x67\xf3\x7b\xe8\x53\x8f\x5a\x8b\xe7\x40\xe4\x84" } } } }; gcry_cipher_hd_t hde, hdd; unsigned char out[MAX_DATA_LEN]; int i, j, keylen, blklen; gcry_error_t err = 0; if (verbose) fprintf (stderr, " Starting OFB checks.\n"); for (i = 0; i < sizeof (tv) / sizeof (tv[0]); i++) { if (gcry_cipher_test_algo (tv[i].algo) && in_fips_mode) { if (verbose) fprintf (stderr, " algorithm %d not available in fips mode\n", tv[i].algo); continue; } if (verbose) fprintf (stderr, " checking OFB mode for %s [%i]\n", gcry_cipher_algo_name (tv[i].algo), tv[i].algo); err = gcry_cipher_open (&hde, tv[i].algo, GCRY_CIPHER_MODE_OFB, 0); if (!err) err = gcry_cipher_open (&hdd, tv[i].algo, GCRY_CIPHER_MODE_OFB, 0); if (err) { fail ("aes-ofb, gcry_cipher_open failed: %s\n", gpg_strerror (err)); return; } keylen = gcry_cipher_get_algo_keylen(tv[i].algo); if (!keylen) { fail ("aes-ofb, gcry_cipher_get_algo_keylen failed\n"); return; } err = gcry_cipher_setkey (hde, tv[i].key, keylen); if (!err) err = gcry_cipher_setkey (hdd, tv[i].key, keylen); if (err) { fail ("aes-ofb, gcry_cipher_setkey failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } blklen = gcry_cipher_get_algo_blklen(tv[i].algo); if (!blklen) { fail ("aes-ofb, gcry_cipher_get_algo_blklen failed\n"); return; } err = gcry_cipher_setiv (hde, tv[i].iv, blklen); if (!err) err = gcry_cipher_setiv (hdd, tv[i].iv, blklen); if (err) { fail ("aes-ofb, gcry_cipher_setiv failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } for (j = 0; tv[i].data[j].inlen; j++) { err = gcry_cipher_encrypt (hde, out, MAX_DATA_LEN, tv[i].data[j].plaintext, tv[i].data[j].inlen); if (err) { fail ("aes-ofb, gcry_cipher_encrypt (%d, %d) failed: %s\n", i, j, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } if (memcmp (tv[i].data[j].out, out, tv[i].data[j].inlen)) fail ("aes-ofb, encrypt mismatch entry %d:%d\n", i, j); err = gcry_cipher_decrypt (hdd, out, tv[i].data[j].inlen, NULL, 0); if (err) { fail ("aes-ofb, gcry_cipher_decrypt (%d, %d) failed: %s\n", i, j, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } if (memcmp (tv[i].data[j].plaintext, out, tv[i].data[j].inlen)) fail ("aes-ofb, decrypt mismatch entry %d:%d\n", i, j); } err = gcry_cipher_reset(hde); if (!err) err = gcry_cipher_reset(hdd); if (err) { fail ("aes-ofb, gcry_cipher_reset (%d, %d) failed: %s\n", i, j, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } /* gcry_cipher_reset clears the IV */ err = gcry_cipher_setiv (hde, tv[i].iv, blklen); if (!err) err = gcry_cipher_setiv (hdd, tv[i].iv, blklen); if (err) { fail ("aes-ofb, gcry_cipher_setiv failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } /* this time we encrypt and decrypt one byte at a time */ for (j = 0; tv[i].data[j].inlen; j++) { int byteNum; for (byteNum = 0; byteNum < tv[i].data[j].inlen; ++byteNum) { err = gcry_cipher_encrypt (hde, out+byteNum, 1, (tv[i].data[j].plaintext) + byteNum, 1); if (err) { fail ("aes-ofb, gcry_cipher_encrypt (%d, %d) failed: %s\n", i, j, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } } if (memcmp (tv[i].data[j].out, out, tv[i].data[j].inlen)) fail ("aes-ofb, encrypt mismatch entry %d:%d\n", i, j); for (byteNum = 0; byteNum < tv[i].data[j].inlen; ++byteNum) { err = gcry_cipher_decrypt (hdd, out+byteNum, 1, NULL, 0); if (err) { fail ("aes-ofb, gcry_cipher_decrypt (%d, %d) failed: %s\n", i, j, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } } if (memcmp (tv[i].data[j].plaintext, out, tv[i].data[j].inlen)) fail ("aes-ofb, decrypt mismatch entry %d:%d\n", i, j); } gcry_cipher_close (hde); gcry_cipher_close (hdd); } if (verbose) fprintf (stderr, " Completed OFB checks.\n"); } static void _check_gcm_cipher (unsigned int step) { struct tv { int algo; char key[MAX_DATA_LEN]; char iv[MAX_DATA_LEN]; int ivlen; unsigned char aad[MAX_DATA_LEN]; int aadlen; unsigned char plaintext[MAX_DATA_LEN]; int inlen; char out[MAX_DATA_LEN]; char tag[MAX_DATA_LEN]; int taglen; int should_fail; } tv[] = { /* http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/gcm/gcm-revised-spec.pdf */ { GCRY_CIPHER_AES, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 12, "", 0, "", 0, "", "\x58\xe2\xfc\xce\xfa\x7e\x30\x61\x36\x7f\x1d\x57\xa4\xe7\x45\x5a" }, { GCRY_CIPHER_AES, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 12, "", 0, "", 0, "", "\x58\xe2\xfc\xce\xfa\x7e\x30\x61\x36\x7f\x1d\x57\xa4\xe7\x45", 15 }, { GCRY_CIPHER_AES, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 12, "", 0, "", 0, "", "\x58\xe2\xfc\xce\xfa\x7e\x30\x61\x36\x7f\x1d\x57\xa4\xe7", 14 }, { GCRY_CIPHER_AES, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 12, "", 0, "", 0, "", "\x58\xe2\xfc\xce\xfa\x7e\x30\x61\x36\x7f\x1d\x57\xa4", 13 }, { GCRY_CIPHER_AES, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 12, "", 0, "", 0, "", "\x58\xe2\xfc\xce\xfa\x7e\x30\x61\x36\x7f\x1d\x57", 12 }, { GCRY_CIPHER_AES, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 12, "", 0, "", 0, "", "\x58\xe2\xfc\xce\xfa\x7e\x30\x61\x36\x7f\x1d", 11, 1 }, { GCRY_CIPHER_AES, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 12, "", 0, "", 0, "", "\x58\xe2\xfc\xce\xfa\x7e\x30\x61", 8 }, { GCRY_CIPHER_AES, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 12, "", 0, "", 0, "", "\x58\xe2\xfc\xce", 4 }, { GCRY_CIPHER_AES, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 12, "", 0, "", 0, "", "\x58", 1, 1 }, { GCRY_CIPHER_AES, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 12, "", 0, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 16, "\x03\x88\xda\xce\x60\xb6\xa3\x92\xf3\x28\xc2\xb9\x71\xb2\xfe\x78", "\xab\x6e\x47\xd4\x2c\xec\x13\xbd\xf5\x3a\x67\xb2\x12\x57\xbd\xdf" }, { GCRY_CIPHER_AES, "\xfe\xff\xe9\x92\x86\x65\x73\x1c\x6d\x6a\x8f\x94\x67\x30\x83\x08", "\xca\xfe\xba\xbe\xfa\xce\xdb\xad\xde\xca\xf8\x88", 12, "", 0, "\xd9\x31\x32\x25\xf8\x84\x06\xe5\xa5\x59\x09\xc5\xaf\xf5\x26\x9a" "\x86\xa7\xa9\x53\x15\x34\xf7\xda\x2e\x4c\x30\x3d\x8a\x31\x8a\x72" "\x1c\x3c\x0c\x95\x95\x68\x09\x53\x2f\xcf\x0e\x24\x49\xa6\xb5\x25" "\xb1\x6a\xed\xf5\xaa\x0d\xe6\x57\xba\x63\x7b\x39\x1a\xaf\xd2\x55", 64, "\x42\x83\x1e\xc2\x21\x77\x74\x24\x4b\x72\x21\xb7\x84\xd0\xd4\x9c" "\xe3\xaa\x21\x2f\x2c\x02\xa4\xe0\x35\xc1\x7e\x23\x29\xac\xa1\x2e" "\x21\xd5\x14\xb2\x54\x66\x93\x1c\x7d\x8f\x6a\x5a\xac\x84\xaa\x05" "\x1b\xa3\x0b\x39\x6a\x0a\xac\x97\x3d\x58\xe0\x91\x47\x3f\x59\x85", "\x4d\x5c\x2a\xf3\x27\xcd\x64\xa6\x2c\xf3\x5a\xbd\x2b\xa6\xfa\xb4" }, { GCRY_CIPHER_AES, "\xfe\xff\xe9\x92\x86\x65\x73\x1c\x6d\x6a\x8f\x94\x67\x30\x83\x08", "\xca\xfe\xba\xbe\xfa\xce\xdb\xad\xde\xca\xf8\x88", 12, "\xfe\xed\xfa\xce\xde\xad\xbe\xef\xfe\xed\xfa\xce\xde\xad\xbe\xef" "\xab\xad\xda\xd2", 20, "\xd9\x31\x32\x25\xf8\x84\x06\xe5\xa5\x59\x09\xc5\xaf\xf5\x26\x9a" "\x86\xa7\xa9\x53\x15\x34\xf7\xda\x2e\x4c\x30\x3d\x8a\x31\x8a\x72" "\x1c\x3c\x0c\x95\x95\x68\x09\x53\x2f\xcf\x0e\x24\x49\xa6\xb5\x25" "\xb1\x6a\xed\xf5\xaa\x0d\xe6\x57\xba\x63\x7b\x39", 60, "\x42\x83\x1e\xc2\x21\x77\x74\x24\x4b\x72\x21\xb7\x84\xd0\xd4\x9c" "\xe3\xaa\x21\x2f\x2c\x02\xa4\xe0\x35\xc1\x7e\x23\x29\xac\xa1\x2e" "\x21\xd5\x14\xb2\x54\x66\x93\x1c\x7d\x8f\x6a\x5a\xac\x84\xaa\x05" "\x1b\xa3\x0b\x39\x6a\x0a\xac\x97\x3d\x58\xe0\x91\x47\x3f\x59\x85", "\x5b\xc9\x4f\xbc\x32\x21\xa5\xdb\x94\xfa\xe9\x5a\xe7\x12\x1a\x47" }, { GCRY_CIPHER_AES, "\xfe\xff\xe9\x92\x86\x65\x73\x1c\x6d\x6a\x8f\x94\x67\x30\x83\x08", "\xca\xfe\xba\xbe\xfa\xce\xdb\xad", 8, "\xfe\xed\xfa\xce\xde\xad\xbe\xef\xfe\xed\xfa\xce\xde\xad\xbe\xef" "\xab\xad\xda\xd2", 20, "\xd9\x31\x32\x25\xf8\x84\x06\xe5\xa5\x59\x09\xc5\xaf\xf5\x26\x9a" "\x86\xa7\xa9\x53\x15\x34\xf7\xda\x2e\x4c\x30\x3d\x8a\x31\x8a\x72" "\x1c\x3c\x0c\x95\x95\x68\x09\x53\x2f\xcf\x0e\x24\x49\xa6\xb5\x25" "\xb1\x6a\xed\xf5\xaa\x0d\xe6\x57\xba\x63\x7b\x39", 60, "\x61\x35\x3b\x4c\x28\x06\x93\x4a\x77\x7f\xf5\x1f\xa2\x2a\x47\x55" "\x69\x9b\x2a\x71\x4f\xcd\xc6\xf8\x37\x66\xe5\xf9\x7b\x6c\x74\x23" "\x73\x80\x69\x00\xe4\x9f\x24\xb2\x2b\x09\x75\x44\xd4\x89\x6b\x42" "\x49\x89\xb5\xe1\xeb\xac\x0f\x07\xc2\x3f\x45\x98", "\x36\x12\xd2\xe7\x9e\x3b\x07\x85\x56\x1b\xe1\x4a\xac\xa2\xfc\xcb" }, { GCRY_CIPHER_AES, "\xfe\xff\xe9\x92\x86\x65\x73\x1c\x6d\x6a\x8f\x94\x67\x30\x83\x08", "\x93\x13\x22\x5d\xf8\x84\x06\xe5\x55\x90\x9c\x5a\xff\x52\x69\xaa" "\x6a\x7a\x95\x38\x53\x4f\x7d\xa1\xe4\xc3\x03\xd2\xa3\x18\xa7\x28" "\xc3\xc0\xc9\x51\x56\x80\x95\x39\xfc\xf0\xe2\x42\x9a\x6b\x52\x54" "\x16\xae\xdb\xf5\xa0\xde\x6a\x57\xa6\x37\xb3\x9b", 60, "\xfe\xed\xfa\xce\xde\xad\xbe\xef\xfe\xed\xfa\xce\xde\xad\xbe\xef" "\xab\xad\xda\xd2", 20, "\xd9\x31\x32\x25\xf8\x84\x06\xe5\xa5\x59\x09\xc5\xaf\xf5\x26\x9a" "\x86\xa7\xa9\x53\x15\x34\xf7\xda\x2e\x4c\x30\x3d\x8a\x31\x8a\x72" "\x1c\x3c\x0c\x95\x95\x68\x09\x53\x2f\xcf\x0e\x24\x49\xa6\xb5\x25" "\xb1\x6a\xed\xf5\xaa\x0d\xe6\x57\xba\x63\x7b\x39", 60, "\x8c\xe2\x49\x98\x62\x56\x15\xb6\x03\xa0\x33\xac\xa1\x3f\xb8\x94" "\xbe\x91\x12\xa5\xc3\xa2\x11\xa8\xba\x26\x2a\x3c\xca\x7e\x2c\xa7" "\x01\xe4\xa9\xa4\xfb\xa4\x3c\x90\xcc\xdc\xb2\x81\xd4\x8c\x7c\x6f" "\xd6\x28\x75\xd2\xac\xa4\x17\x03\x4c\x34\xae\xe5", "\x61\x9c\xc5\xae\xff\xfe\x0b\xfa\x46\x2a\xf4\x3c\x16\x99\xd0\x50" }, { GCRY_CIPHER_AES192, "\xfe\xff\xe9\x92\x86\x65\x73\x1c\x6d\x6a\x8f\x94\x67\x30\x83\x08" "\xfe\xff\xe9\x92\x86\x65\x73\x1c", "\x93\x13\x22\x5d\xf8\x84\x06\xe5\x55\x90\x9c\x5a\xff\x52\x69\xaa" "\x6a\x7a\x95\x38\x53\x4f\x7d\xa1\xe4\xc3\x03\xd2\xa3\x18\xa7\x28" "\xc3\xc0\xc9\x51\x56\x80\x95\x39\xfc\xf0\xe2\x42\x9a\x6b\x52\x54" "\x16\xae\xdb\xf5\xa0\xde\x6a\x57\xa6\x37\xb3\x9b", 60, "\xfe\xed\xfa\xce\xde\xad\xbe\xef\xfe\xed\xfa\xce\xde\xad\xbe\xef" "\xab\xad\xda\xd2", 20, "\xd9\x31\x32\x25\xf8\x84\x06\xe5\xa5\x59\x09\xc5\xaf\xf5\x26\x9a" "\x86\xa7\xa9\x53\x15\x34\xf7\xda\x2e\x4c\x30\x3d\x8a\x31\x8a\x72" "\x1c\x3c\x0c\x95\x95\x68\x09\x53\x2f\xcf\x0e\x24\x49\xa6\xb5\x25" "\xb1\x6a\xed\xf5\xaa\x0d\xe6\x57\xba\x63\x7b\x39", 60, "\xd2\x7e\x88\x68\x1c\xe3\x24\x3c\x48\x30\x16\x5a\x8f\xdc\xf9\xff" "\x1d\xe9\xa1\xd8\xe6\xb4\x47\xef\x6e\xf7\xb7\x98\x28\x66\x6e\x45" "\x81\xe7\x90\x12\xaf\x34\xdd\xd9\xe2\xf0\x37\x58\x9b\x29\x2d\xb3" "\xe6\x7c\x03\x67\x45\xfa\x22\xe7\xe9\xb7\x37\x3b", "\xdc\xf5\x66\xff\x29\x1c\x25\xbb\xb8\x56\x8f\xc3\xd3\x76\xa6\xd9" }, { GCRY_CIPHER_AES256, "\xfe\xff\xe9\x92\x86\x65\x73\x1c\x6d\x6a\x8f\x94\x67\x30\x83\x08" "\xfe\xff\xe9\x92\x86\x65\x73\x1c\x6d\x6a\x8f\x94\x67\x30\x83\x08", "\x93\x13\x22\x5d\xf8\x84\x06\xe5\x55\x90\x9c\x5a\xff\x52\x69\xaa" "\x6a\x7a\x95\x38\x53\x4f\x7d\xa1\xe4\xc3\x03\xd2\xa3\x18\xa7\x28" "\xc3\xc0\xc9\x51\x56\x80\x95\x39\xfc\xf0\xe2\x42\x9a\x6b\x52\x54" "\x16\xae\xdb\xf5\xa0\xde\x6a\x57\xa6\x37\xb3\x9b", 60, "\xfe\xed\xfa\xce\xde\xad\xbe\xef\xfe\xed\xfa\xce\xde\xad\xbe\xef" "\xab\xad\xda\xd2", 20, "\xd9\x31\x32\x25\xf8\x84\x06\xe5\xa5\x59\x09\xc5\xaf\xf5\x26\x9a" "\x86\xa7\xa9\x53\x15\x34\xf7\xda\x2e\x4c\x30\x3d\x8a\x31\x8a\x72" "\x1c\x3c\x0c\x95\x95\x68\x09\x53\x2f\xcf\x0e\x24\x49\xa6\xb5\x25" "\xb1\x6a\xed\xf5\xaa\x0d\xe6\x57\xba\x63\x7b\x39", 60, "\x5a\x8d\xef\x2f\x0c\x9e\x53\xf1\xf7\x5d\x78\x53\x65\x9e\x2a\x20" "\xee\xb2\xb2\x2a\xaf\xde\x64\x19\xa0\x58\xab\x4f\x6f\x74\x6b\xf4" "\x0f\xc0\xc3\xb7\x80\xf2\x44\x45\x2d\xa3\xeb\xf1\xc5\xd8\x2c\xde" "\xa2\x41\x89\x97\x20\x0e\xf8\x2e\x44\xae\x7e\x3f", "\xa4\x4a\x82\x66\xee\x1c\x8e\xb0\xc8\xb5\xd4\xcf\x5a\xe9\xf1\x9a" } }; gcry_cipher_hd_t hde, hdd; unsigned char out[MAX_DATA_LEN]; unsigned char tag[GCRY_GCM_BLOCK_LEN]; int i, keylen; gcry_error_t err = 0; size_t pos, poslen, taglen2; int byteNum; if (verbose) fprintf (stderr, " Starting GCM checks.\n"); for (i = 0; i < sizeof (tv) / sizeof (tv[0]); i++) { if (gcry_cipher_test_algo (tv[i].algo) && in_fips_mode) { if (verbose) fprintf (stderr, " algorithm %d not available in fips mode\n", tv[i].algo); continue; } if (verbose) fprintf (stderr, " checking GCM mode for %s [%i]\n", gcry_cipher_algo_name (tv[i].algo), tv[i].algo); err = gcry_cipher_open (&hde, tv[i].algo, GCRY_CIPHER_MODE_GCM, 0); if (!err) err = gcry_cipher_open (&hdd, tv[i].algo, GCRY_CIPHER_MODE_GCM, 0); if (err) { fail ("aes-gcm, gcry_cipher_open failed: %s\n", gpg_strerror (err)); return; } keylen = gcry_cipher_get_algo_keylen(tv[i].algo); if (!keylen) { fail ("aes-gcm, gcry_cipher_get_algo_keylen failed\n"); return; } err = gcry_cipher_setkey (hde, tv[i].key, keylen); if (!err) err = gcry_cipher_setkey (hdd, tv[i].key, keylen); if (err) { fail ("aes-gcm, gcry_cipher_setkey failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } err = gcry_cipher_setiv (hde, tv[i].iv, tv[i].ivlen); if (!err) err = gcry_cipher_setiv (hdd, tv[i].iv, tv[i].ivlen); if (err) { fail ("aes-gcm, gcry_cipher_setiv failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } err = gcry_cipher_info (hde, GCRYCTL_GET_TAGLEN, NULL, &taglen2); if (err) { fail ("cipher-gcm, gcryctl_get_taglen failed (tv %d): %s\n", i, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } if (taglen2 != GCRY_GCM_BLOCK_LEN) { fail ("cipher-gcm, gcryctl_get_taglen returned bad length" " (tv %d): got=%zu want=%d\n", i, taglen2, GCRY_GCM_BLOCK_LEN); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } for (pos = 0; pos < tv[i].aadlen; pos += step) { poslen = (pos + step < tv[i].aadlen) ? step : tv[i].aadlen - pos; err = gcry_cipher_authenticate(hde, tv[i].aad + pos, poslen); if (err) { fail ("aes-gcm, gcry_cipher_authenticate (%d) (%lu:%d) failed: " "%s\n", i, (unsigned long) pos, step, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } err = gcry_cipher_authenticate(hdd, tv[i].aad + pos, poslen); if (err) { fail ("aes-gcm, de gcry_cipher_authenticate (%d) (%lu:%d) failed: " "%s\n", i, (unsigned long) pos, step, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } } for (pos = 0; pos < tv[i].inlen; pos += step) { poslen = (pos + step < tv[i].inlen) ? step : tv[i].inlen - pos; err = gcry_cipher_encrypt (hde, out + pos, poslen, tv[i].plaintext + pos, poslen); if (err) { fail ("aes-gcm, gcry_cipher_encrypt (%d) (%lu:%d) failed: %s\n", i, (unsigned long) pos, step, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } } if (memcmp (tv[i].out, out, tv[i].inlen)) fail ("aes-gcm, encrypt mismatch entry %d (step %d)\n", i, step); for (pos = 0; pos < tv[i].inlen; pos += step) { poslen = (pos + step < tv[i].inlen) ? step : tv[i].inlen - pos; err = gcry_cipher_decrypt (hdd, out + pos, poslen, NULL, 0); if (err) { fail ("aes-gcm, gcry_cipher_decrypt (%d) (%lu:%d) failed: %s\n", i, (unsigned long) pos, step, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } } if (memcmp (tv[i].plaintext, out, tv[i].inlen)) fail ("aes-gcm, decrypt mismatch entry %d (step %d)\n", i, step); taglen2 = tv[i].taglen ? tv[i].taglen : GCRY_GCM_BLOCK_LEN; err = gcry_cipher_gettag (hde, out, taglen2); if (err) { if (tv[i].should_fail) goto next_tv; fail ("aes-gcm, gcry_cipher_gettag(%d) failed: %s\n", i, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } if (memcmp (tv[i].tag, out, taglen2)) fail ("aes-gcm, encrypt tag mismatch entry %d\n", i); err = gcry_cipher_checktag (hdd, out, taglen2); if (err) { fail ("aes-gcm, gcry_cipher_checktag(%d) failed: %s\n", i, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } err = gcry_cipher_reset(hde); if (!err) err = gcry_cipher_reset(hdd); if (err) { fail ("aes-gcm, gcry_cipher_reset (%d) failed: %s\n", i, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } /* gcry_cipher_reset clears the IV */ err = gcry_cipher_setiv (hde, tv[i].iv, tv[i].ivlen); if (!err) err = gcry_cipher_setiv (hdd, tv[i].iv, tv[i].ivlen); if (err) { fail ("aes-gcm, gcry_cipher_setiv failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } /* this time we authenticate, encrypt and decrypt one byte at a time */ for (byteNum = 0; byteNum < tv[i].aadlen; ++byteNum) { err = gcry_cipher_authenticate(hde, tv[i].aad + byteNum, 1); if (err) { fail ("aes-gcm, gcry_cipher_authenticate (%d) (byte-buf) failed: " "%s\n", i, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } err = gcry_cipher_authenticate(hdd, tv[i].aad + byteNum, 1); if (err) { fail ("aes-gcm, de gcry_cipher_authenticate (%d) (byte-buf) " "failed: %s\n", i, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } } for (byteNum = 0; byteNum < tv[i].inlen; ++byteNum) { err = gcry_cipher_encrypt (hde, out+byteNum, 1, (tv[i].plaintext) + byteNum, 1); if (err) { fail ("aes-gcm, gcry_cipher_encrypt (%d) (byte-buf) failed: %s\n", i, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } } if (memcmp (tv[i].out, out, tv[i].inlen)) fail ("aes-gcm, encrypt mismatch entry %d, (byte-buf)\n", i); /* Test output to larger than 16-byte buffer. */ taglen2 = tv[i].taglen ? tv[i].taglen : GCRY_GCM_BLOCK_LEN + 1; err = gcry_cipher_gettag (hde, tag, taglen2); if (err) { if (tv[i].should_fail) goto next_tv; fail ("aes-gcm, gcry_cipher_gettag(%d, %lu) (byte-buf) failed: %s\n", i, (unsigned long) taglen2, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } taglen2 = tv[i].taglen ? tv[i].taglen : GCRY_GCM_BLOCK_LEN; if (memcmp (tv[i].tag, tag, taglen2)) fail ("aes-gcm, encrypt tag mismatch entry %d, (byte-buf)\n", i); for (byteNum = 0; byteNum < tv[i].inlen; ++byteNum) { err = gcry_cipher_decrypt (hdd, out+byteNum, 1, NULL, 0); if (err) { fail ("aes-gcm, gcry_cipher_decrypt (%d) (byte-buf) failed: %s\n", i, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } } if (memcmp (tv[i].plaintext, out, tv[i].inlen)) fail ("aes-gcm, decrypt mismatch entry %d\n", i); err = gcry_cipher_checktag (hdd, tag, taglen2); if (err) { fail ("aes-gcm, gcry_cipher_checktag(%d) (byte-buf) failed: %s\n", i, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } err = gcry_cipher_checktag (hdd, tag, 1); if (!err) { fail ("aes-gcm, gcry_cipher_checktag(%d) did not fail for invalid " " tag length of '%d'\n", i, 1); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } err = gcry_cipher_checktag (hdd, tag, 17); if (!err) { fail ("aes-gcm, gcry_cipher_checktag(%d) did not fail for invalid " " tag length of '%d'\n", i, 17); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } if (tv[i].should_fail) { fail ("aes-gcm, negative test succeeded %d\n", i); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } next_tv: gcry_cipher_close (hde); gcry_cipher_close (hdd); } if (verbose) fprintf (stderr, " Completed GCM checks.\n"); } static void check_gcm_cipher (void) { /* Large buffers, no splitting. */ _check_gcm_cipher(0xffffffff); /* Split input to one byte buffers. */ _check_gcm_cipher(1); /* Split input to 7 byte buffers. */ _check_gcm_cipher(7); /* Split input to 16 byte buffers. */ _check_gcm_cipher(16); } static void _check_poly1305_cipher (unsigned int step) { struct tv { int algo; const char *key; const char *iv; int ivlen; const char *aad; int aadlen; const char *plaintext; int inlen; const char *out; const char *tag; } tv[] = { /* draft-irtf-cfrg-chacha20-poly1305-03 */ { GCRY_CIPHER_CHACHA20, "\x1c\x92\x40\xa5\xeb\x55\xd3\x8a\xf3\x33\x88\x86\x04\xf6\xb5\xf0" "\x47\x39\x17\xc1\x40\x2b\x80\x09\x9d\xca\x5c\xbc\x20\x70\x75\xc0", "\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x07\x08", 12, "\xf3\x33\x88\x86\x00\x00\x00\x00\x00\x00\x4e\x91", 12, "\x49\x6e\x74\x65\x72\x6e\x65\x74\x2d\x44\x72\x61\x66\x74\x73\x20" "\x61\x72\x65\x20\x64\x72\x61\x66\x74\x20\x64\x6f\x63\x75\x6d\x65" "\x6e\x74\x73\x20\x76\x61\x6c\x69\x64\x20\x66\x6f\x72\x20\x61\x20" "\x6d\x61\x78\x69\x6d\x75\x6d\x20\x6f\x66\x20\x73\x69\x78\x20\x6d" "\x6f\x6e\x74\x68\x73\x20\x61\x6e\x64\x20\x6d\x61\x79\x20\x62\x65" "\x20\x75\x70\x64\x61\x74\x65\x64\x2c\x20\x72\x65\x70\x6c\x61\x63" "\x65\x64\x2c\x20\x6f\x72\x20\x6f\x62\x73\x6f\x6c\x65\x74\x65\x64" "\x20\x62\x79\x20\x6f\x74\x68\x65\x72\x20\x64\x6f\x63\x75\x6d\x65" "\x6e\x74\x73\x20\x61\x74\x20\x61\x6e\x79\x20\x74\x69\x6d\x65\x2e" "\x20\x49\x74\x20\x69\x73\x20\x69\x6e\x61\x70\x70\x72\x6f\x70\x72" "\x69\x61\x74\x65\x20\x74\x6f\x20\x75\x73\x65\x20\x49\x6e\x74\x65" "\x72\x6e\x65\x74\x2d\x44\x72\x61\x66\x74\x73\x20\x61\x73\x20\x72" "\x65\x66\x65\x72\x65\x6e\x63\x65\x20\x6d\x61\x74\x65\x72\x69\x61" "\x6c\x20\x6f\x72\x20\x74\x6f\x20\x63\x69\x74\x65\x20\x74\x68\x65" "\x6d\x20\x6f\x74\x68\x65\x72\x20\x74\x68\x61\x6e\x20\x61\x73\x20" "\x2f\xe2\x80\x9c\x77\x6f\x72\x6b\x20\x69\x6e\x20\x70\x72\x6f\x67" "\x72\x65\x73\x73\x2e\x2f\xe2\x80\x9d", 265, "\x64\xa0\x86\x15\x75\x86\x1a\xf4\x60\xf0\x62\xc7\x9b\xe6\x43\xbd" "\x5e\x80\x5c\xfd\x34\x5c\xf3\x89\xf1\x08\x67\x0a\xc7\x6c\x8c\xb2" "\x4c\x6c\xfc\x18\x75\x5d\x43\xee\xa0\x9e\xe9\x4e\x38\x2d\x26\xb0" "\xbd\xb7\xb7\x3c\x32\x1b\x01\x00\xd4\xf0\x3b\x7f\x35\x58\x94\xcf" "\x33\x2f\x83\x0e\x71\x0b\x97\xce\x98\xc8\xa8\x4a\xbd\x0b\x94\x81" "\x14\xad\x17\x6e\x00\x8d\x33\xbd\x60\xf9\x82\xb1\xff\x37\xc8\x55" "\x97\x97\xa0\x6e\xf4\xf0\xef\x61\xc1\x86\x32\x4e\x2b\x35\x06\x38" "\x36\x06\x90\x7b\x6a\x7c\x02\xb0\xf9\xf6\x15\x7b\x53\xc8\x67\xe4" "\xb9\x16\x6c\x76\x7b\x80\x4d\x46\xa5\x9b\x52\x16\xcd\xe7\xa4\xe9" "\x90\x40\xc5\xa4\x04\x33\x22\x5e\xe2\x82\xa1\xb0\xa0\x6c\x52\x3e" "\xaf\x45\x34\xd7\xf8\x3f\xa1\x15\x5b\x00\x47\x71\x8c\xbc\x54\x6a" "\x0d\x07\x2b\x04\xb3\x56\x4e\xea\x1b\x42\x22\x73\xf5\x48\x27\x1a" "\x0b\xb2\x31\x60\x53\xfa\x76\x99\x19\x55\xeb\xd6\x31\x59\x43\x4e" "\xce\xbb\x4e\x46\x6d\xae\x5a\x10\x73\xa6\x72\x76\x27\x09\x7a\x10" "\x49\xe6\x17\xd9\x1d\x36\x10\x94\xfa\x68\xf0\xff\x77\x98\x71\x30" "\x30\x5b\xea\xba\x2e\xda\x04\xdf\x99\x7b\x71\x4d\x6c\x6f\x2c\x29" "\xa6\xad\x5c\xb4\x02\x2b\x02\x70\x9b", "\xee\xad\x9d\x67\x89\x0c\xbb\x22\x39\x23\x36\xfe\xa1\x85\x1f\x38" }, /* draft-irtf-cfrg-chacha20-poly1305-03 */ { GCRY_CIPHER_CHACHA20, "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f" "\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f", "\x07\x00\x00\x00\x40\x41\x42\x43\x44\x45\x46\x47", 12, "\x50\x51\x52\x53\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7", 12, "Ladies and Gentlemen of the class of '99: If I could offer you " "only one tip for the future, sunscreen would be it.", 114, "\xd3\x1a\x8d\x34\x64\x8e\x60\xdb\x7b\x86\xaf\xbc\x53\xef\x7e\xc2" "\xa4\xad\xed\x51\x29\x6e\x08\xfe\xa9\xe2\xb5\xa7\x36\xee\x62\xd6" "\x3d\xbe\xa4\x5e\x8c\xa9\x67\x12\x82\xfa\xfb\x69\xda\x92\x72\x8b" "\x1a\x71\xde\x0a\x9e\x06\x0b\x29\x05\xd6\xa5\xb6\x7e\xcd\x3b\x36" "\x92\xdd\xbd\x7f\x2d\x77\x8b\x8c\x98\x03\xae\xe3\x28\x09\x1b\x58" "\xfa\xb3\x24\xe4\xfa\xd6\x75\x94\x55\x85\x80\x8b\x48\x31\xd7\xbc" "\x3f\xf4\xde\xf0\x8e\x4b\x7a\x9d\xe5\x76\xd2\x65\x86\xce\xc6\x4b" "\x61\x16", "\x1a\xe1\x0b\x59\x4f\x09\xe2\x6a\x7e\x90\x2e\xcb\xd0\x60\x06\x91" }, }; gcry_cipher_hd_t hde, hdd; unsigned char out[1024]; unsigned char tag[16]; int i, keylen; gcry_error_t err = 0; size_t pos, poslen, taglen2; int byteNum; if (verbose) fprintf (stderr, " Starting POLY1305 checks.\n"); for (i = 0; i < sizeof (tv) / sizeof (tv[0]); i++) { if (verbose) fprintf (stderr, " checking POLY1305 mode for %s [%i]\n", gcry_cipher_algo_name (tv[i].algo), tv[i].algo); err = gcry_cipher_open (&hde, tv[i].algo, GCRY_CIPHER_MODE_POLY1305, 0); if (!err) err = gcry_cipher_open (&hdd, tv[i].algo, GCRY_CIPHER_MODE_POLY1305, 0); if (err) { fail ("poly1305, gcry_cipher_open failed: %s\n", gpg_strerror (err)); return; } keylen = gcry_cipher_get_algo_keylen(tv[i].algo); if (!keylen) { fail ("poly1305, gcry_cipher_get_algo_keylen failed\n"); return; } err = gcry_cipher_setkey (hde, tv[i].key, keylen); if (!err) err = gcry_cipher_setkey (hdd, tv[i].key, keylen); if (err) { fail ("poly1305, gcry_cipher_setkey failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } err = gcry_cipher_setiv (hde, tv[i].iv, tv[i].ivlen); if (!err) err = gcry_cipher_setiv (hdd, tv[i].iv, tv[i].ivlen); if (err) { fail ("poly1305, gcry_cipher_setiv failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } err = gcry_cipher_info (hde, GCRYCTL_GET_TAGLEN, NULL, &taglen2); if (err) { fail ("cipher-poly1305, gcryctl_get_taglen failed (tv %d): %s\n", i, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } if (taglen2 != 16) { fail ("cipher-poly1305, gcryctl_get_taglen returned bad length" " (tv %d): got=%zu want=%d\n", i, taglen2, 16); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } for (pos = 0; pos < tv[i].aadlen; pos += step) { poslen = (pos + step < tv[i].aadlen) ? step : tv[i].aadlen - pos; err = gcry_cipher_authenticate(hde, tv[i].aad + pos, poslen); if (err) { fail ("poly1305, gcry_cipher_authenticate (%d) (%lu:%d) failed: " "%s\n", i, (unsigned long) pos, step, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } err = gcry_cipher_authenticate(hdd, tv[i].aad + pos, poslen); if (err) { fail ("poly1305, de gcry_cipher_authenticate (%d) (%lu:%d) failed: " "%s\n", i, (unsigned long) pos, step, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } } for (pos = 0; pos < tv[i].inlen; pos += step) { poslen = (pos + step < tv[i].inlen) ? step : tv[i].inlen - pos; err = gcry_cipher_encrypt (hde, out + pos, poslen, tv[i].plaintext + pos, poslen); if (err) { fail ("poly1305, gcry_cipher_encrypt (%d) (%lu:%d) failed: %s\n", i, (unsigned long) pos, step, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } } if (memcmp (tv[i].out, out, tv[i].inlen)) fail ("poly1305, encrypt mismatch entry %d (step %d)\n", i, step); for (pos = 0; pos < tv[i].inlen; pos += step) { poslen = (pos + step < tv[i].inlen) ? step : tv[i].inlen - pos; err = gcry_cipher_decrypt (hdd, out + pos, poslen, NULL, 0); if (err) { fail ("poly1305, gcry_cipher_decrypt (%d) (%lu:%d) failed: %s\n", i, (unsigned long) pos, step, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } } if (memcmp (tv[i].plaintext, out, tv[i].inlen)) fail ("poly1305, decrypt mismatch entry %d (step %d)\n", i, step); err = gcry_cipher_gettag (hde, out, 16); if (err) { fail ("poly1305, gcry_cipher_gettag(%d) failed: %s\n", i, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } if (memcmp (tv[i].tag, out, 16)) fail ("poly1305, encrypt tag mismatch entry %d\n", i); err = gcry_cipher_checktag (hdd, out, 16); if (err) { fail ("poly1305, gcry_cipher_checktag(%d) failed: %s\n", i, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } err = gcry_cipher_reset(hde); if (!err) err = gcry_cipher_reset(hdd); if (err) { fail ("poly1305, gcry_cipher_reset (%d) failed: %s\n", i, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } /* gcry_cipher_reset clears the IV */ err = gcry_cipher_setiv (hde, tv[i].iv, tv[i].ivlen); if (!err) err = gcry_cipher_setiv (hdd, tv[i].iv, tv[i].ivlen); if (err) { fail ("poly1305, gcry_cipher_setiv failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } /* this time we authenticate, encrypt and decrypt one byte at a time */ for (byteNum = 0; byteNum < tv[i].aadlen; ++byteNum) { err = gcry_cipher_authenticate(hde, tv[i].aad + byteNum, 1); if (err) { fail ("poly1305, gcry_cipher_authenticate (%d) (byte-buf) failed: " "%s\n", i, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } err = gcry_cipher_authenticate(hdd, tv[i].aad + byteNum, 1); if (err) { fail ("poly1305, de gcry_cipher_authenticate (%d) (byte-buf) " "failed: %s\n", i, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } } for (byteNum = 0; byteNum < tv[i].inlen; ++byteNum) { err = gcry_cipher_encrypt (hde, out+byteNum, 1, (tv[i].plaintext) + byteNum, 1); if (err) { fail ("poly1305, gcry_cipher_encrypt (%d) (byte-buf) failed: %s\n", i, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } } if (memcmp (tv[i].out, out, tv[i].inlen)) fail ("poly1305, encrypt mismatch entry %d, (byte-buf)\n", i); err = gcry_cipher_gettag (hde, tag, 16); if (err) { fail ("poly1305, gcry_cipher_gettag(%d) (byte-buf) failed: %s\n", i, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } if (memcmp (tv[i].tag, tag, 16)) fail ("poly1305, encrypt tag mismatch entry %d, (byte-buf)\n", i); for (byteNum = 0; byteNum < tv[i].inlen; ++byteNum) { err = gcry_cipher_decrypt (hdd, out+byteNum, 1, NULL, 0); if (err) { fail ("poly1305, gcry_cipher_decrypt (%d) (byte-buf) failed: %s\n", i, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } } if (memcmp (tv[i].plaintext, out, tv[i].inlen)) fail ("poly1305, decrypt mismatch entry %d\n", i); err = gcry_cipher_checktag (hdd, tag, 16); if (err) { fail ("poly1305, gcry_cipher_checktag(%d) (byte-buf) failed: %s\n", i, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } gcry_cipher_close (hde); gcry_cipher_close (hdd); } if (verbose) fprintf (stderr, " Completed POLY1305 checks.\n"); } static void check_poly1305_cipher (void) { /* Large buffers, no splitting. */ _check_poly1305_cipher(0xffffffff); /* Split input to one byte buffers. */ _check_poly1305_cipher(1); /* Split input to 7 byte buffers. */ _check_poly1305_cipher(7); /* Split input to 16 byte buffers. */ _check_poly1305_cipher(16); } static void check_ccm_cipher (void) { static const struct tv { int algo; int keylen; const char *key; int noncelen; const char *nonce; int aadlen; const char *aad; int plainlen; const char *plaintext; int cipherlen; const char *ciphertext; } tv[] = { /* RFC 3610 */ { GCRY_CIPHER_AES, /* Packet Vector #1 */ 16, "\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF", 13, "\x00\x00\x00\x03\x02\x01\x00\xA0\xA1\xA2\xA3\xA4\xA5", 8, "\x00\x01\x02\x03\x04\x05\x06\x07", 23, "\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E", 31, "\x58\x8C\x97\x9A\x61\xC6\x63\xD2\xF0\x66\xD0\xC2\xC0\xF9\x89\x80\x6D\x5F\x6B\x61\xDA\xC3\x84\x17\xE8\xD1\x2C\xFD\xF9\x26\xE0"}, { GCRY_CIPHER_AES, /* Packet Vector #2 */ 16, "\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF", 13, "\x00\x00\x00\x04\x03\x02\x01\xA0\xA1\xA2\xA3\xA4\xA5", 8, "\x00\x01\x02\x03\x04\x05\x06\x07", 24, "\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F", 32, "\x72\xC9\x1A\x36\xE1\x35\xF8\xCF\x29\x1C\xA8\x94\x08\x5C\x87\xE3\xCC\x15\xC4\x39\xC9\xE4\x3A\x3B\xA0\x91\xD5\x6E\x10\x40\x09\x16"}, { GCRY_CIPHER_AES, /* Packet Vector #3 */ 16, "\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF", 13, "\x00\x00\x00\x05\x04\x03\x02\xA0\xA1\xA2\xA3\xA4\xA5", 8, "\x00\x01\x02\x03\x04\x05\x06\x07", 25, "\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\x20", 33, "\x51\xB1\xE5\xF4\x4A\x19\x7D\x1D\xA4\x6B\x0F\x8E\x2D\x28\x2A\xE8\x71\xE8\x38\xBB\x64\xDA\x85\x96\x57\x4A\xDA\xA7\x6F\xBD\x9F\xB0\xC5"}, { GCRY_CIPHER_AES, /* Packet Vector #4 */ 16, "\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF", 13, "\x00\x00\x00\x06\x05\x04\x03\xA0\xA1\xA2\xA3\xA4\xA5", 12, "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B", 19, "\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E", 27, "\xA2\x8C\x68\x65\x93\x9A\x9A\x79\xFA\xAA\x5C\x4C\x2A\x9D\x4A\x91\xCD\xAC\x8C\x96\xC8\x61\xB9\xC9\xE6\x1E\xF1"}, { GCRY_CIPHER_AES, /* Packet Vector #5 */ 16, "\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF", 13, "\x00\x00\x00\x07\x06\x05\x04\xA0\xA1\xA2\xA3\xA4\xA5", 12, "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B", 20, "\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F", 28, "\xDC\xF1\xFB\x7B\x5D\x9E\x23\xFB\x9D\x4E\x13\x12\x53\x65\x8A\xD8\x6E\xBD\xCA\x3E\x51\xE8\x3F\x07\x7D\x9C\x2D\x93"}, { GCRY_CIPHER_AES, /* Packet Vector #6 */ 16, "\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF", 13, "\x00\x00\x00\x08\x07\x06\x05\xA0\xA1\xA2\xA3\xA4\xA5", 12, "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B", 21, "\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\x20", 29, "\x6F\xC1\xB0\x11\xF0\x06\x56\x8B\x51\x71\xA4\x2D\x95\x3D\x46\x9B\x25\x70\xA4\xBD\x87\x40\x5A\x04\x43\xAC\x91\xCB\x94"}, { GCRY_CIPHER_AES, /* Packet Vector #7 */ 16, "\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF", 13, "\x00\x00\x00\x09\x08\x07\x06\xA0\xA1\xA2\xA3\xA4\xA5", 8, "\x00\x01\x02\x03\x04\x05\x06\x07", 23, "\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E", 33, "\x01\x35\xD1\xB2\xC9\x5F\x41\xD5\xD1\xD4\xFE\xC1\x85\xD1\x66\xB8\x09\x4E\x99\x9D\xFE\xD9\x6C\x04\x8C\x56\x60\x2C\x97\xAC\xBB\x74\x90"}, { GCRY_CIPHER_AES, /* Packet Vector #8 */ 16, "\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF", 13, "\x00\x00\x00\x0A\x09\x08\x07\xA0\xA1\xA2\xA3\xA4\xA5", 8, "\x00\x01\x02\x03\x04\x05\x06\x07", 24, "\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F", 34, "\x7B\x75\x39\x9A\xC0\x83\x1D\xD2\xF0\xBB\xD7\x58\x79\xA2\xFD\x8F\x6C\xAE\x6B\x6C\xD9\xB7\xDB\x24\xC1\x7B\x44\x33\xF4\x34\x96\x3F\x34\xB4"}, { GCRY_CIPHER_AES, /* Packet Vector #9 */ 16, "\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF", 13, "\x00\x00\x00\x0B\x0A\x09\x08\xA0\xA1\xA2\xA3\xA4\xA5", 8, "\x00\x01\x02\x03\x04\x05\x06\x07", 25, "\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\x20", 35, "\x82\x53\x1A\x60\xCC\x24\x94\x5A\x4B\x82\x79\x18\x1A\xB5\xC8\x4D\xF2\x1C\xE7\xF9\xB7\x3F\x42\xE1\x97\xEA\x9C\x07\xE5\x6B\x5E\xB1\x7E\x5F\x4E"}, { GCRY_CIPHER_AES, /* Packet Vector #10 */ 16, "\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF", 13, "\x00\x00\x00\x0C\x0B\x0A\x09\xA0\xA1\xA2\xA3\xA4\xA5", 12, "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B", 19, "\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E", 29, "\x07\x34\x25\x94\x15\x77\x85\x15\x2B\x07\x40\x98\x33\x0A\xBB\x14\x1B\x94\x7B\x56\x6A\xA9\x40\x6B\x4D\x99\x99\x88\xDD"}, { GCRY_CIPHER_AES, /* Packet Vector #11 */ 16, "\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF", 13, "\x00\x00\x00\x0D\x0C\x0B\x0A\xA0\xA1\xA2\xA3\xA4\xA5", 12, "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B", 20, "\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F", 30, "\x67\x6B\xB2\x03\x80\xB0\xE3\x01\xE8\xAB\x79\x59\x0A\x39\x6D\xA7\x8B\x83\x49\x34\xF5\x3A\xA2\xE9\x10\x7A\x8B\x6C\x02\x2C"}, { GCRY_CIPHER_AES, /* Packet Vector #12 */ 16, "\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF", 13, "\x00\x00\x00\x0E\x0D\x0C\x0B\xA0\xA1\xA2\xA3\xA4\xA5", 12, "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B", 21, "\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\x20", 31, "\xC0\xFF\xA0\xD6\xF0\x5B\xDB\x67\xF2\x4D\x43\xA4\x33\x8D\x2A\xA4\xBE\xD7\xB2\x0E\x43\xCD\x1A\xA3\x16\x62\xE7\xAD\x65\xD6\xDB"}, { GCRY_CIPHER_AES, /* Packet Vector #13 */ 16, "\xD7\x82\x8D\x13\xB2\xB0\xBD\xC3\x25\xA7\x62\x36\xDF\x93\xCC\x6B", 13, "\x00\x41\x2B\x4E\xA9\xCD\xBE\x3C\x96\x96\x76\x6C\xFA", 8, "\x0B\xE1\xA8\x8B\xAC\xE0\x18\xB1", 23, "\x08\xE8\xCF\x97\xD8\x20\xEA\x25\x84\x60\xE9\x6A\xD9\xCF\x52\x89\x05\x4D\x89\x5C\xEA\xC4\x7C", 31, "\x4C\xB9\x7F\x86\xA2\xA4\x68\x9A\x87\x79\x47\xAB\x80\x91\xEF\x53\x86\xA6\xFF\xBD\xD0\x80\xF8\xE7\x8C\xF7\xCB\x0C\xDD\xD7\xB3"}, { GCRY_CIPHER_AES, /* Packet Vector #14 */ 16, "\xD7\x82\x8D\x13\xB2\xB0\xBD\xC3\x25\xA7\x62\x36\xDF\x93\xCC\x6B", 13, "\x00\x33\x56\x8E\xF7\xB2\x63\x3C\x96\x96\x76\x6C\xFA", 8, "\x63\x01\x8F\x76\xDC\x8A\x1B\xCB", 24, "\x90\x20\xEA\x6F\x91\xBD\xD8\x5A\xFA\x00\x39\xBA\x4B\xAF\xF9\xBF\xB7\x9C\x70\x28\x94\x9C\xD0\xEC", 32, "\x4C\xCB\x1E\x7C\xA9\x81\xBE\xFA\xA0\x72\x6C\x55\xD3\x78\x06\x12\x98\xC8\x5C\x92\x81\x4A\xBC\x33\xC5\x2E\xE8\x1D\x7D\x77\xC0\x8A"}, { GCRY_CIPHER_AES, /* Packet Vector #15 */ 16, "\xD7\x82\x8D\x13\xB2\xB0\xBD\xC3\x25\xA7\x62\x36\xDF\x93\xCC\x6B", 13, "\x00\x10\x3F\xE4\x13\x36\x71\x3C\x96\x96\x76\x6C\xFA", 8, "\xAA\x6C\xFA\x36\xCA\xE8\x6B\x40", 25, "\xB9\x16\xE0\xEA\xCC\x1C\x00\xD7\xDC\xEC\x68\xEC\x0B\x3B\xBB\x1A\x02\xDE\x8A\x2D\x1A\xA3\x46\x13\x2E", 33, "\xB1\xD2\x3A\x22\x20\xDD\xC0\xAC\x90\x0D\x9A\xA0\x3C\x61\xFC\xF4\xA5\x59\xA4\x41\x77\x67\x08\x97\x08\xA7\x76\x79\x6E\xDB\x72\x35\x06"}, { GCRY_CIPHER_AES, /* Packet Vector #16 */ 16, "\xD7\x82\x8D\x13\xB2\xB0\xBD\xC3\x25\xA7\x62\x36\xDF\x93\xCC\x6B", 13, "\x00\x76\x4C\x63\xB8\x05\x8E\x3C\x96\x96\x76\x6C\xFA", 12, "\xD0\xD0\x73\x5C\x53\x1E\x1B\xEC\xF0\x49\xC2\x44", 19, "\x12\xDA\xAC\x56\x30\xEF\xA5\x39\x6F\x77\x0C\xE1\xA6\x6B\x21\xF7\xB2\x10\x1C", 27, "\x14\xD2\x53\xC3\x96\x7B\x70\x60\x9B\x7C\xBB\x7C\x49\x91\x60\x28\x32\x45\x26\x9A\x6F\x49\x97\x5B\xCA\xDE\xAF"}, { GCRY_CIPHER_AES, /* Packet Vector #17 */ 16, "\xD7\x82\x8D\x13\xB2\xB0\xBD\xC3\x25\xA7\x62\x36\xDF\x93\xCC\x6B", 13, "\x00\xF8\xB6\x78\x09\x4E\x3B\x3C\x96\x96\x76\x6C\xFA", 12, "\x77\xB6\x0F\x01\x1C\x03\xE1\x52\x58\x99\xBC\xAE", 20, "\xE8\x8B\x6A\x46\xC7\x8D\x63\xE5\x2E\xB8\xC5\x46\xEF\xB5\xDE\x6F\x75\xE9\xCC\x0D", 28, "\x55\x45\xFF\x1A\x08\x5E\xE2\xEF\xBF\x52\xB2\xE0\x4B\xEE\x1E\x23\x36\xC7\x3E\x3F\x76\x2C\x0C\x77\x44\xFE\x7E\x3C"}, { GCRY_CIPHER_AES, /* Packet Vector #18 */ 16, "\xD7\x82\x8D\x13\xB2\xB0\xBD\xC3\x25\xA7\x62\x36\xDF\x93\xCC\x6B", 13, "\x00\xD5\x60\x91\x2D\x3F\x70\x3C\x96\x96\x76\x6C\xFA", 12, "\xCD\x90\x44\xD2\xB7\x1F\xDB\x81\x20\xEA\x60\xC0", 21, "\x64\x35\xAC\xBA\xFB\x11\xA8\x2E\x2F\x07\x1D\x7C\xA4\xA5\xEB\xD9\x3A\x80\x3B\xA8\x7F", 29, "\x00\x97\x69\xEC\xAB\xDF\x48\x62\x55\x94\xC5\x92\x51\xE6\x03\x57\x22\x67\x5E\x04\xC8\x47\x09\x9E\x5A\xE0\x70\x45\x51"}, { GCRY_CIPHER_AES, /* Packet Vector #19 */ 16, "\xD7\x82\x8D\x13\xB2\xB0\xBD\xC3\x25\xA7\x62\x36\xDF\x93\xCC\x6B", 13, "\x00\x42\xFF\xF8\xF1\x95\x1C\x3C\x96\x96\x76\x6C\xFA", 8, "\xD8\x5B\xC7\xE6\x9F\x94\x4F\xB8", 23, "\x8A\x19\xB9\x50\xBC\xF7\x1A\x01\x8E\x5E\x67\x01\xC9\x17\x87\x65\x98\x09\xD6\x7D\xBE\xDD\x18", 33, "\xBC\x21\x8D\xAA\x94\x74\x27\xB6\xDB\x38\x6A\x99\xAC\x1A\xEF\x23\xAD\xE0\xB5\x29\x39\xCB\x6A\x63\x7C\xF9\xBE\xC2\x40\x88\x97\xC6\xBA"}, { GCRY_CIPHER_AES, /* Packet Vector #20 */ 16, "\xD7\x82\x8D\x13\xB2\xB0\xBD\xC3\x25\xA7\x62\x36\xDF\x93\xCC\x6B", 13, "\x00\x92\x0F\x40\xE5\x6C\xDC\x3C\x96\x96\x76\x6C\xFA", 8, "\x74\xA0\xEB\xC9\x06\x9F\x5B\x37", 24, "\x17\x61\x43\x3C\x37\xC5\xA3\x5F\xC1\xF3\x9F\x40\x63\x02\xEB\x90\x7C\x61\x63\xBE\x38\xC9\x84\x37", 34, "\x58\x10\xE6\xFD\x25\x87\x40\x22\xE8\x03\x61\xA4\x78\xE3\xE9\xCF\x48\x4A\xB0\x4F\x44\x7E\xFF\xF6\xF0\xA4\x77\xCC\x2F\xC9\xBF\x54\x89\x44"}, { GCRY_CIPHER_AES, /* Packet Vector #21 */ 16, "\xD7\x82\x8D\x13\xB2\xB0\xBD\xC3\x25\xA7\x62\x36\xDF\x93\xCC\x6B", 13, "\x00\x27\xCA\x0C\x71\x20\xBC\x3C\x96\x96\x76\x6C\xFA", 8, "\x44\xA3\xAA\x3A\xAE\x64\x75\xCA", 25, "\xA4\x34\xA8\xE5\x85\x00\xC6\xE4\x15\x30\x53\x88\x62\xD6\x86\xEA\x9E\x81\x30\x1B\x5A\xE4\x22\x6B\xFA", 35, "\xF2\xBE\xED\x7B\xC5\x09\x8E\x83\xFE\xB5\xB3\x16\x08\xF8\xE2\x9C\x38\x81\x9A\x89\xC8\xE7\x76\xF1\x54\x4D\x41\x51\xA4\xED\x3A\x8B\x87\xB9\xCE"}, { GCRY_CIPHER_AES, /* Packet Vector #22 */ 16, "\xD7\x82\x8D\x13\xB2\xB0\xBD\xC3\x25\xA7\x62\x36\xDF\x93\xCC\x6B", 13, "\x00\x5B\x8C\xCB\xCD\x9A\xF8\x3C\x96\x96\x76\x6C\xFA", 12, "\xEC\x46\xBB\x63\xB0\x25\x20\xC3\x3C\x49\xFD\x70", 19, "\xB9\x6B\x49\xE2\x1D\x62\x17\x41\x63\x28\x75\xDB\x7F\x6C\x92\x43\xD2\xD7\xC2", 29, "\x31\xD7\x50\xA0\x9D\xA3\xED\x7F\xDD\xD4\x9A\x20\x32\xAA\xBF\x17\xEC\x8E\xBF\x7D\x22\xC8\x08\x8C\x66\x6B\xE5\xC1\x97"}, { GCRY_CIPHER_AES, /* Packet Vector #23 */ 16, "\xD7\x82\x8D\x13\xB2\xB0\xBD\xC3\x25\xA7\x62\x36\xDF\x93\xCC\x6B", 13, "\x00\x3E\xBE\x94\x04\x4B\x9A\x3C\x96\x96\x76\x6C\xFA", 12, "\x47\xA6\x5A\xC7\x8B\x3D\x59\x42\x27\xE8\x5E\x71", 20, "\xE2\xFC\xFB\xB8\x80\x44\x2C\x73\x1B\xF9\x51\x67\xC8\xFF\xD7\x89\x5E\x33\x70\x76", 30, "\xE8\x82\xF1\xDB\xD3\x8C\xE3\xED\xA7\xC2\x3F\x04\xDD\x65\x07\x1E\xB4\x13\x42\xAC\xDF\x7E\x00\xDC\xCE\xC7\xAE\x52\x98\x7D"}, { GCRY_CIPHER_AES, /* Packet Vector #24 */ 16, "\xD7\x82\x8D\x13\xB2\xB0\xBD\xC3\x25\xA7\x62\x36\xDF\x93\xCC\x6B", 13, "\x00\x8D\x49\x3B\x30\xAE\x8B\x3C\x96\x96\x76\x6C\xFA", 12, "\x6E\x37\xA6\xEF\x54\x6D\x95\x5D\x34\xAB\x60\x59", 21, "\xAB\xF2\x1C\x0B\x02\xFE\xB8\x8F\x85\x6D\xF4\xA3\x73\x81\xBC\xE3\xCC\x12\x85\x17\xD4", 31, "\xF3\x29\x05\xB8\x8A\x64\x1B\x04\xB9\xC9\xFF\xB5\x8C\xC3\x90\x90\x0F\x3D\xA1\x2A\xB1\x6D\xCE\x9E\x82\xEF\xA1\x6D\xA6\x20\x59"}, /* RFC 5528 */ { GCRY_CIPHER_CAMELLIA128, /* Packet Vector #1 */ 16, "\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF", 13, "\x00\x00\x00\x03\x02\x01\x00\xA0\xA1\xA2\xA3\xA4\xA5", 8, "\x00\x01\x02\x03\x04\x05\x06\x07", 23, "\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E", 31, "\xBA\x73\x71\x85\xE7\x19\x31\x04\x92\xF3\x8A\x5F\x12\x51\xDA\x55\xFA\xFB\xC9\x49\x84\x8A\x0D\xFC\xAE\xCE\x74\x6B\x3D\xB9\xAD"}, { GCRY_CIPHER_CAMELLIA128, /* Packet Vector #2 */ 16, "\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF", 13, "\x00\x00\x00\x04\x03\x02\x01\xA0\xA1\xA2\xA3\xA4\xA5", 8, "\x00\x01\x02\x03\x04\x05\x06\x07", 24, "\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F", 32, "\x5D\x25\x64\xBF\x8E\xAF\xE1\xD9\x95\x26\xEC\x01\x6D\x1B\xF0\x42\x4C\xFB\xD2\xCD\x62\x84\x8F\x33\x60\xB2\x29\x5D\xF2\x42\x83\xE8"}, { GCRY_CIPHER_CAMELLIA128, /* Packet Vector #3 */ 16, "\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF", 13, "\x00\x00\x00\x05\x04\x03\x02\xA0\xA1\xA2\xA3\xA4\xA5", 8, "\x00\x01\x02\x03\x04\x05\x06\x07", 25, "\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\x20", 33, "\x81\xF6\x63\xD6\xC7\x78\x78\x17\xF9\x20\x36\x08\xB9\x82\xAD\x15\xDC\x2B\xBD\x87\xD7\x56\xF7\x92\x04\xF5\x51\xD6\x68\x2F\x23\xAA\x46"}, { GCRY_CIPHER_CAMELLIA128, /* Packet Vector #4 */ 16, "\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF", 13, "\x00\x00\x00\x06\x05\x04\x03\xA0\xA1\xA2\xA3\xA4\xA5", 12, "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B", 19, "\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E", 27, "\xCA\xEF\x1E\x82\x72\x11\xB0\x8F\x7B\xD9\x0F\x08\xC7\x72\x88\xC0\x70\xA4\xA0\x8B\x3A\x93\x3A\x63\xE4\x97\xA0"}, { GCRY_CIPHER_CAMELLIA128, /* Packet Vector #5 */ 16, "\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF", 13, "\x00\x00\x00\x07\x06\x05\x04\xA0\xA1\xA2\xA3\xA4\xA5", 12, "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B", 20, "\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F", 28, "\x2A\xD3\xBA\xD9\x4F\xC5\x2E\x92\xBE\x43\x8E\x82\x7C\x10\x23\xB9\x6A\x8A\x77\x25\x8F\xA1\x7B\xA7\xF3\x31\xDB\x09"}, { GCRY_CIPHER_CAMELLIA128, /* Packet Vector #6 */ 16, "\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF", 13, "\x00\x00\x00\x08\x07\x06\x05\xA0\xA1\xA2\xA3\xA4\xA5", 12, "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B", 21, "\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\x20", 29, "\xFE\xA5\x48\x0B\xA5\x3F\xA8\xD3\xC3\x44\x22\xAA\xCE\x4D\xE6\x7F\xFA\x3B\xB7\x3B\xAB\xAB\x36\xA1\xEE\x4F\xE0\xFE\x28"}, { GCRY_CIPHER_CAMELLIA128, /* Packet Vector #7 */ 16, "\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF", 13, "\x00\x00\x00\x09\x08\x07\x06\xA0\xA1\xA2\xA3\xA4\xA5", 8, "\x00\x01\x02\x03\x04\x05\x06\x07", 23, "\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E", 33, "\x54\x53\x20\x26\xE5\x4C\x11\x9A\x8D\x36\xD9\xEC\x6E\x1E\xD9\x74\x16\xC8\x70\x8C\x4B\x5C\x2C\xAC\xAF\xA3\xBC\xCF\x7A\x4E\xBF\x95\x73"}, { GCRY_CIPHER_CAMELLIA128, /* Packet Vector #8 */ 16, "\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF", 13, "\x00\x00\x00\x0A\x09\x08\x07\xA0\xA1\xA2\xA3\xA4\xA5", 8, "\x00\x01\x02\x03\x04\x05\x06\x07", 24, "\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F", 34, "\x8A\xD1\x9B\x00\x1A\x87\xD1\x48\xF4\xD9\x2B\xEF\x34\x52\x5C\xCC\xE3\xA6\x3C\x65\x12\xA6\xF5\x75\x73\x88\xE4\x91\x3E\xF1\x47\x01\xF4\x41"}, { GCRY_CIPHER_CAMELLIA128, /* Packet Vector #9 */ 16, "\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF", 13, "\x00\x00\x00\x0B\x0A\x09\x08\xA0\xA1\xA2\xA3\xA4\xA5", 8, "\x00\x01\x02\x03\x04\x05\x06\x07", 25, "\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\x20", 35, "\x5D\xB0\x8D\x62\x40\x7E\x6E\x31\xD6\x0F\x9C\xA2\xC6\x04\x74\x21\x9A\xC0\xBE\x50\xC0\xD4\xA5\x77\x87\x94\xD6\xE2\x30\xCD\x25\xC9\xFE\xBF\x87"}, { GCRY_CIPHER_CAMELLIA128, /* Packet Vector #10 */ 16, "\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF", 13, "\x00\x00\x00\x0C\x0B\x0A\x09\xA0\xA1\xA2\xA3\xA4\xA5", 12, "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B", 19, "\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E", 29, "\xDB\x11\x8C\xCE\xC1\xB8\x76\x1C\x87\x7C\xD8\x96\x3A\x67\xD6\xF3\xBB\xBC\x5C\xD0\x92\x99\xEB\x11\xF3\x12\xF2\x32\x37"}, { GCRY_CIPHER_CAMELLIA128, /* Packet Vector #11 */ 16, "\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF", 13, "\x00\x00\x00\x0D\x0C\x0B\x0A\xA0\xA1\xA2\xA3\xA4\xA5", 12, "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B", 20, "\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F", 30, "\x7C\xC8\x3D\x8D\xC4\x91\x03\x52\x5B\x48\x3D\xC5\xCA\x7E\xA9\xAB\x81\x2B\x70\x56\x07\x9D\xAF\xFA\xDA\x16\xCC\xCF\x2C\x4E"}, { GCRY_CIPHER_CAMELLIA128, /* Packet Vector #12 */ 16, "\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF", 13, "\x00\x00\x00\x0E\x0D\x0C\x0B\xA0\xA1\xA2\xA3\xA4\xA5", 12, "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B", 21, "\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\x20", 31, "\x2C\xD3\x5B\x88\x20\xD2\x3E\x7A\xA3\x51\xB0\xE9\x2F\xC7\x93\x67\x23\x8B\x2C\xC7\x48\xCB\xB9\x4C\x29\x47\x79\x3D\x64\xAF\x75"}, { GCRY_CIPHER_CAMELLIA128, /* Packet Vector #13 */ 16, "\xD7\x5C\x27\x78\x07\x8C\xA9\x3D\x97\x1F\x96\xFD\xE7\x20\xF4\xCD", 13, "\x00\xA9\x70\x11\x0E\x19\x27\xB1\x60\xB6\xA3\x1C\x1C", 8, "\x6B\x7F\x46\x45\x07\xFA\xE4\x96", 23, "\xC6\xB5\xF3\xE6\xCA\x23\x11\xAE\xF7\x47\x2B\x20\x3E\x73\x5E\xA5\x61\xAD\xB1\x7D\x56\xC5\xA3", 31, "\xA4\x35\xD7\x27\x34\x8D\xDD\x22\x90\x7F\x7E\xB8\xF5\xFD\xBB\x4D\x93\x9D\xA6\x52\x4D\xB4\xF6\x45\x58\xC0\x2D\x25\xB1\x27\xEE"}, { GCRY_CIPHER_CAMELLIA128, /* Packet Vector #14 */ 16, "\xD7\x5C\x27\x78\x07\x8C\xA9\x3D\x97\x1F\x96\xFD\xE7\x20\xF4\xCD", 13, "\x00\x83\xCD\x8C\xE0\xCB\x42\xB1\x60\xB6\xA3\x1C\x1C", 8, "\x98\x66\x05\xB4\x3D\xF1\x5D\xE7", 24, "\x01\xF6\xCE\x67\x64\xC5\x74\x48\x3B\xB0\x2E\x6B\xBF\x1E\x0A\xBD\x26\xA2\x25\x72\xB4\xD8\x0E\xE7", 32, "\x8A\xE0\x52\x50\x8F\xBE\xCA\x93\x2E\x34\x6F\x05\xE0\xDC\x0D\xFB\xCF\x93\x9E\xAF\xFA\x3E\x58\x7C\x86\x7D\x6E\x1C\x48\x70\x38\x06"}, { GCRY_CIPHER_CAMELLIA128, /* Packet Vector #15 */ 16, "\xD7\x5C\x27\x78\x07\x8C\xA9\x3D\x97\x1F\x96\xFD\xE7\x20\xF4\xCD", 13, "\x00\x5F\x54\x95\x0B\x18\xF2\xB1\x60\xB6\xA3\x1C\x1C", 8, "\x48\xF2\xE7\xE1\xA7\x67\x1A\x51", 25, "\xCD\xF1\xD8\x40\x6F\xC2\xE9\x01\x49\x53\x89\x70\x05\xFB\xFB\x8B\xA5\x72\x76\xF9\x24\x04\x60\x8E\x08", 33, "\x08\xB6\x7E\xE2\x1C\x8B\xF2\x6E\x47\x3E\x40\x85\x99\xE9\xC0\x83\x6D\x6A\xF0\xBB\x18\xDF\x55\x46\x6C\xA8\x08\x78\xA7\x90\x47\x6D\xE5"}, { GCRY_CIPHER_CAMELLIA128, /* Packet Vector #16 */ 16, "\xD7\x5C\x27\x78\x07\x8C\xA9\x3D\x97\x1F\x96\xFD\xE7\x20\xF4\xCD", 13, "\x00\xEC\x60\x08\x63\x31\x9A\xB1\x60\xB6\xA3\x1C\x1C", 12, "\xDE\x97\xDF\x3B\x8C\xBD\x6D\x8E\x50\x30\xDA\x4C", 19, "\xB0\x05\xDC\xFA\x0B\x59\x18\x14\x26\xA9\x61\x68\x5A\x99\x3D\x8C\x43\x18\x5B", 27, "\x63\xB7\x8B\x49\x67\xB1\x9E\xDB\xB7\x33\xCD\x11\x14\xF6\x4E\xB2\x26\x08\x93\x68\xC3\x54\x82\x8D\x95\x0C\xC5"}, { GCRY_CIPHER_CAMELLIA128, /* Packet Vector #17 */ 16, "\xD7\x5C\x27\x78\x07\x8C\xA9\x3D\x97\x1F\x96\xFD\xE7\x20\xF4\xCD", 13, "\x00\x60\xCF\xF1\xA3\x1E\xA1\xB1\x60\xB6\xA3\x1C\x1C", 12, "\xA5\xEE\x93\xE4\x57\xDF\x05\x46\x6E\x78\x2D\xCF", 20, "\x2E\x20\x21\x12\x98\x10\x5F\x12\x9D\x5E\xD9\x5B\x93\xF7\x2D\x30\xB2\xFA\xCC\xD7", 28, "\x0B\xC6\xBB\xE2\xA8\xB9\x09\xF4\x62\x9E\xE6\xDC\x14\x8D\xA4\x44\x10\xE1\x8A\xF4\x31\x47\x38\x32\x76\xF6\x6A\x9F"}, { GCRY_CIPHER_CAMELLIA128, /* Packet Vector #18 */ 16, "\xD7\x5C\x27\x78\x07\x8C\xA9\x3D\x97\x1F\x96\xFD\xE7\x20\xF4\xCD", 13, "\x00\x0F\x85\xCD\x99\x5C\x97\xB1\x60\xB6\xA3\x1C\x1C", 12, "\x24\xAA\x1B\xF9\xA5\xCD\x87\x61\x82\xA2\x50\x74", 21, "\x26\x45\x94\x1E\x75\x63\x2D\x34\x91\xAF\x0F\xC0\xC9\x87\x6C\x3B\xE4\xAA\x74\x68\xC9", 29, "\x22\x2A\xD6\x32\xFA\x31\xD6\xAF\x97\x0C\x34\x5F\x7E\x77\xCA\x3B\xD0\xDC\x25\xB3\x40\xA1\xA3\xD3\x1F\x8D\x4B\x44\xB7"}, { GCRY_CIPHER_CAMELLIA128, /* Packet Vector #19 */ 16, "\xD7\x5C\x27\x78\x07\x8C\xA9\x3D\x97\x1F\x96\xFD\xE7\x20\xF4\xCD", 13, "\x00\xC2\x9B\x2C\xAA\xC4\xCD\xB1\x60\xB6\xA3\x1C\x1C", 8, "\x69\x19\x46\xB9\xCA\x07\xBE\x87", 23, "\x07\x01\x35\xA6\x43\x7C\x9D\xB1\x20\xCD\x61\xD8\xF6\xC3\x9C\x3E\xA1\x25\xFD\x95\xA0\xD2\x3D", 33, "\x05\xB8\xE1\xB9\xC4\x9C\xFD\x56\xCF\x13\x0A\xA6\x25\x1D\xC2\xEC\xC0\x6C\xCC\x50\x8F\xE6\x97\xA0\x06\x6D\x57\xC8\x4B\xEC\x18\x27\x68"}, { GCRY_CIPHER_CAMELLIA128, /* Packet Vector #20 */ 16, "\xD7\x5C\x27\x78\x07\x8C\xA9\x3D\x97\x1F\x96\xFD\xE7\x20\xF4\xCD", 13, "\x00\x2C\x6B\x75\x95\xEE\x62\xB1\x60\xB6\xA3\x1C\x1C", 8, "\xD0\xC5\x4E\xCB\x84\x62\x7D\xC4", 24, "\xC8\xC0\x88\x0E\x6C\x63\x6E\x20\x09\x3D\xD6\x59\x42\x17\xD2\xE1\x88\x77\xDB\x26\x4E\x71\xA5\xCC", 34, "\x54\xCE\xB9\x68\xDE\xE2\x36\x11\x57\x5E\xC0\x03\xDF\xAA\x1C\xD4\x88\x49\xBD\xF5\xAE\x2E\xDB\x6B\x7F\xA7\x75\xB1\x50\xED\x43\x83\xC5\xA9"}, { GCRY_CIPHER_CAMELLIA128, /* Packet Vector #21 */ 16, "\xD7\x5C\x27\x78\x07\x8C\xA9\x3D\x97\x1F\x96\xFD\xE7\x20\xF4\xCD", 13, "\x00\xC5\x3C\xD4\xC2\xAA\x24\xB1\x60\xB6\xA3\x1C\x1C", 8, "\xE2\x85\xE0\xE4\x80\x8C\xDA\x3D", 25, "\xF7\x5D\xAA\x07\x10\xC4\xE6\x42\x97\x79\x4D\xC2\xB7\xD2\xA2\x07\x57\xB1\xAA\x4E\x44\x80\x02\xFF\xAB", 35, "\xB1\x40\x45\x46\xBF\x66\x72\x10\xCA\x28\xE3\x09\xB3\x9B\xD6\xCA\x7E\x9F\xC8\x28\x5F\xE6\x98\xD4\x3C\xD2\x0A\x02\xE0\xBD\xCA\xED\x20\x10\xD3"}, { GCRY_CIPHER_CAMELLIA128, /* Packet Vector #22 */ 16, "\xD7\x5C\x27\x78\x07\x8C\xA9\x3D\x97\x1F\x96\xFD\xE7\x20\xF4\xCD", 13, "\x00\xBE\xE9\x26\x7F\xBA\xDC\xB1\x60\xB6\xA3\x1C\x1C", 12, "\x6C\xAE\xF9\x94\x11\x41\x57\x0D\x7C\x81\x34\x05", 19, "\xC2\x38\x82\x2F\xAC\x5F\x98\xFF\x92\x94\x05\xB0\xAD\x12\x7A\x4E\x41\x85\x4E", 29, "\x94\xC8\x95\x9C\x11\x56\x9A\x29\x78\x31\xA7\x21\x00\x58\x57\xAB\x61\xB8\x7A\x2D\xEA\x09\x36\xB6\xEB\x5F\x62\x5F\x5D"}, { GCRY_CIPHER_CAMELLIA128, /* Packet Vector #23 */ 16, "\xD7\x5C\x27\x78\x07\x8C\xA9\x3D\x97\x1F\x96\xFD\xE7\x20\xF4\xCD", 13, "\x00\xDF\xA8\xB1\x24\x50\x07\xB1\x60\xB6\xA3\x1C\x1C", 12, "\x36\xA5\x2C\xF1\x6B\x19\xA2\x03\x7A\xB7\x01\x1E", 20, "\x4D\xBF\x3E\x77\x4A\xD2\x45\xE5\xD5\x89\x1F\x9D\x1C\x32\xA0\xAE\x02\x2C\x85\xD7", 30, "\x58\x69\xE3\xAA\xD2\x44\x7C\x74\xE0\xFC\x05\xF9\xA4\xEA\x74\x57\x7F\x4D\xE8\xCA\x89\x24\x76\x42\x96\xAD\x04\x11\x9C\xE7"}, { GCRY_CIPHER_CAMELLIA128, /* Packet Vector #24 */ 16, "\xD7\x5C\x27\x78\x07\x8C\xA9\x3D\x97\x1F\x96\xFD\xE7\x20\xF4\xCD", 13, "\x00\x3B\x8F\xD8\xD3\xA9\x37\xB1\x60\xB6\xA3\x1C\x1C", 12, "\xA4\xD4\x99\xF7\x84\x19\x72\x8C\x19\x17\x8B\x0C", 21, "\x9D\xC9\xED\xAE\x2F\xF5\xDF\x86\x36\xE8\xC6\xDE\x0E\xED\x55\xF7\x86\x7E\x33\x33\x7D", 31, "\x4B\x19\x81\x56\x39\x3B\x0F\x77\x96\x08\x6A\xAF\xB4\x54\xF8\xC3\xF0\x34\xCC\xA9\x66\x94\x5F\x1F\xCE\xA7\xE1\x1B\xEE\x6A\x2F"} }; static const int cut[] = { 0, 1, 8, 10, 16, 19, -1 }; gcry_cipher_hd_t hde, hdd; unsigned char out[MAX_DATA_LEN]; u64 ctl_params[3]; int split, aadsplit; size_t j, i, keylen, blklen, authlen, taglen2; gcry_error_t err = 0; if (verbose) fprintf (stderr, " Starting CCM checks.\n"); for (i = 0; i < sizeof (tv) / sizeof (tv[0]); i++) { if (gcry_cipher_test_algo (tv[i].algo) && in_fips_mode) { if (verbose) fprintf (stderr, " algorithm %d not available in fips mode\n", tv[i].algo); continue; } if (verbose) fprintf (stderr, " checking CCM mode for %s [%i]\n", gcry_cipher_algo_name (tv[i].algo), tv[i].algo); for (j = 0; j < sizeof (cut) / sizeof (cut[0]); j++) { split = cut[j] < 0 ? tv[i].plainlen : cut[j]; if (tv[i].plainlen < split) continue; err = gcry_cipher_open (&hde, tv[i].algo, GCRY_CIPHER_MODE_CCM, 0); if (!err) err = gcry_cipher_open (&hdd, tv[i].algo, GCRY_CIPHER_MODE_CCM, 0); if (err) { fail ("cipher-ccm, gcry_cipher_open failed: %s\n", gpg_strerror (err)); return; } keylen = gcry_cipher_get_algo_keylen(tv[i].algo); if (!keylen) { fail ("cipher-ccm, gcry_cipher_get_algo_keylen failed\n"); return; } err = gcry_cipher_setkey (hde, tv[i].key, keylen); if (!err) err = gcry_cipher_setkey (hdd, tv[i].key, keylen); if (err) { fail ("cipher-ccm, gcry_cipher_setkey failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } blklen = gcry_cipher_get_algo_blklen(tv[i].algo); if (!blklen) { fail ("cipher-ccm, gcry_cipher_get_algo_blklen failed\n"); return; } err = gcry_cipher_setiv (hde, tv[i].nonce, tv[i].noncelen); if (!err) err = gcry_cipher_setiv (hdd, tv[i].nonce, tv[i].noncelen); if (err) { fail ("cipher-ccm, gcry_cipher_setiv failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } authlen = tv[i].cipherlen - tv[i].plainlen; ctl_params[0] = tv[i].plainlen; /* encryptedlen */ ctl_params[1] = tv[i].aadlen; /* aadlen */ ctl_params[2] = authlen; /* authtaglen */ err = gcry_cipher_ctl (hde, GCRYCTL_SET_CCM_LENGTHS, ctl_params, sizeof(ctl_params)); if (!err) err = gcry_cipher_ctl (hdd, GCRYCTL_SET_CCM_LENGTHS, ctl_params, sizeof(ctl_params)); if (err) { fail ("cipher-ccm, gcry_cipher_ctl GCRYCTL_SET_CCM_LENGTHS " "failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } err = gcry_cipher_info (hde, GCRYCTL_GET_TAGLEN, NULL, &taglen2); if (err) { fail ("cipher-ccm, gcryctl_get_taglen failed (tv %lu): %s\n", (unsigned long) i, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } if (taglen2 != authlen) { fail ("cipher-ccm, gcryctl_get_taglen returned bad length" " (tv %lu): got=%zu want=%zu\n", (unsigned long) i, taglen2, authlen); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } aadsplit = split > tv[i].aadlen ? 0 : split; err = gcry_cipher_authenticate (hde, tv[i].aad, tv[i].aadlen - aadsplit); if (!err) err = gcry_cipher_authenticate (hde, &tv[i].aad[tv[i].aadlen - aadsplit], aadsplit); if (!err) err = gcry_cipher_authenticate (hdd, tv[i].aad, tv[i].aadlen - aadsplit); if (!err) err = gcry_cipher_authenticate (hdd, &tv[i].aad[tv[i].aadlen - aadsplit], aadsplit); if (err) { fail ("cipher-ccm, gcry_cipher_authenticate failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } err = gcry_cipher_encrypt (hde, out, MAX_DATA_LEN, tv[i].plaintext, tv[i].plainlen - split); if (!err) err = gcry_cipher_encrypt (hde, &out[tv[i].plainlen - split], MAX_DATA_LEN - (tv[i].plainlen - split), &tv[i].plaintext[tv[i].plainlen - split], split); if (err) { fail ("cipher-ccm, gcry_cipher_encrypt (%lu:%lu) failed: %s\n", (unsigned long) i, (unsigned long) j, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } err = gcry_cipher_gettag (hde, &out[tv[i].plainlen], authlen); if (err) { fail ("cipher-ccm, gcry_cipher_gettag (%lu:%lu) failed: %s\n", (unsigned long) i, (unsigned long) j, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } if (memcmp (tv[i].ciphertext, out, tv[i].cipherlen)) fail ("cipher-ccm, encrypt mismatch entry %lu:%lu\n", (unsigned long) i, (unsigned long) j); err = gcry_cipher_decrypt (hdd, out, tv[i].plainlen - split, NULL, 0); if (!err) err = gcry_cipher_decrypt (hdd, &out[tv[i].plainlen - split], split, NULL, 0); if (err) { fail ("cipher-ccm, gcry_cipher_decrypt (%lu:%lu) failed: %s\n", (unsigned long) i, (unsigned long) j, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } if (memcmp (tv[i].plaintext, out, tv[i].plainlen)) fail ("cipher-ccm, decrypt mismatch entry %lu:%lu\n", (unsigned long) i, (unsigned long) j); err = gcry_cipher_checktag (hdd, &out[tv[i].plainlen], authlen); if (err) { fail ("cipher-ccm, gcry_cipher_checktag (%lu:%lu) failed: %s\n", (unsigned long) i, (unsigned long) j, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } gcry_cipher_close (hde); gcry_cipher_close (hdd); } } /* Large buffer tests. */ /* Test encoding of aadlen > 0xfeff. */ { static const char key[]={0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47, 0x48,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f}; static const char iv[]={0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19}; static const char tag[]={0x9C,0x76,0xE7,0x33,0xD5,0x15,0xB3,0x6C, 0xBA,0x76,0x95,0xF7,0xFB,0x91}; char buf[1024]; size_t enclen = 0x20000; size_t aadlen = 0x20000; size_t taglen = sizeof(tag); err = gcry_cipher_open (&hde, GCRY_CIPHER_AES, GCRY_CIPHER_MODE_CCM, 0); if (err) { fail ("cipher-ccm-large, gcry_cipher_open failed: %s\n", gpg_strerror (err)); return; } err = gcry_cipher_setkey (hde, key, sizeof (key)); if (err) { fail ("cipher-ccm-large, gcry_cipher_setkey failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hde); return; } err = gcry_cipher_setiv (hde, iv, sizeof (iv)); if (err) { fail ("cipher-ccm-large, gcry_cipher_setiv failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hde); return; } ctl_params[0] = enclen; /* encryptedlen */ ctl_params[1] = aadlen; /* aadlen */ ctl_params[2] = taglen; /* authtaglen */ err = gcry_cipher_ctl (hde, GCRYCTL_SET_CCM_LENGTHS, ctl_params, sizeof(ctl_params)); if (err) { fail ("cipher-ccm-large, gcry_cipher_ctl GCRYCTL_SET_CCM_LENGTHS " "failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hde); return; } memset (buf, 0xaa, sizeof(buf)); for (i = 0; i < aadlen; i += sizeof(buf)) { err = gcry_cipher_authenticate (hde, buf, sizeof (buf)); if (err) { fail ("cipher-ccm-large, gcry_cipher_authenticate failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hde); return; } } for (i = 0; i < enclen; i += sizeof(buf)) { memset (buf, 0xee, sizeof(buf)); err = gcry_cipher_encrypt (hde, buf, sizeof (buf), NULL, 0); if (err) { fail ("cipher-ccm-large, gcry_cipher_encrypt failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hde); return; } } err = gcry_cipher_gettag (hde, buf, taglen); if (err) { fail ("cipher-ccm-large, gcry_cipher_gettag failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hde); return; } if (memcmp (buf, tag, taglen) != 0) fail ("cipher-ccm-large, encrypt mismatch entry\n"); gcry_cipher_close (hde); } #if 0 /* Test encoding of aadlen > 0xffffffff. */ { static const char key[]={0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47, 0x48,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f}; static const char iv[]={0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19}; static const char tag[]={0x01,0xB2,0xC3,0x4A,0xA6,0x6A,0x07,0x6D, 0xBC,0xBD,0xEA,0x17,0xD3,0x73,0xD7,0xD4}; char buf[1024]; size_t enclen = (size_t)0xffffffff + 1 + 1024; size_t aadlen = (size_t)0xffffffff + 1 + 1024; size_t taglen = sizeof(tag); err = gcry_cipher_open (&hde, GCRY_CIPHER_AES, GCRY_CIPHER_MODE_CCM, 0); if (err) { fail ("cipher-ccm-huge, gcry_cipher_open failed: %s\n", gpg_strerror (err)); return; } err = gcry_cipher_setkey (hde, key, sizeof (key)); if (err) { fail ("cipher-ccm-huge, gcry_cipher_setkey failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hde); return; } err = gcry_cipher_setiv (hde, iv, sizeof (iv)); if (err) { fail ("cipher-ccm-huge, gcry_cipher_setiv failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hde); return; } ctl_params[0] = enclen; /* encryptedlen */ ctl_params[1] = aadlen; /* aadlen */ ctl_params[2] = taglen; /* authtaglen */ err = gcry_cipher_ctl (hde, GCRYCTL_SET_CCM_LENGTHS, ctl_params, sizeof(ctl_params)); if (err) { fail ("cipher-ccm-huge, gcry_cipher_ctl GCRYCTL_SET_CCM_LENGTHS failed:" "%s\n", gpg_strerror (err)); gcry_cipher_close (hde); return; } memset (buf, 0xaa, sizeof(buf)); for (i = 0; i < aadlen; i += sizeof(buf)) { err = gcry_cipher_authenticate (hde, buf, sizeof (buf)); if (err) { fail ("cipher-ccm-huge, gcry_cipher_authenticate failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hde); return; } } for (i = 0; i < enclen; i += sizeof(buf)) { memset (buf, 0xee, sizeof(buf)); err = gcry_cipher_encrypt (hde, buf, sizeof (buf), NULL, 0); if (err) { fail ("cipher-ccm-huge, gcry_cipher_encrypt failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hde); return; } } err = gcry_cipher_gettag (hde, buf, taglen); if (err) { fail ("cipher-ccm-huge, gcry_cipher_gettag failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hde); return; } if (memcmp (buf, tag, taglen) != 0) fail ("cipher-ccm-huge, encrypt mismatch entry\n"); gcry_cipher_close (hde); } if (verbose) fprintf (stderr, " Completed CCM checks.\n"); #endif } static void do_check_ocb_cipher (int inplace) { /* Note that we use hex strings and not binary strings in TV. That makes it easier to maintain the test vectors. */ static const struct { int algo; int taglen; /* 16, 12, or 8 bytes */ const char *key; /* NULL means "000102030405060708090A0B0C0D0E0F" */ const char *nonce; const char *aad; const char *plain; const char *ciph; } tv[] = { /* The RFC-7253 test vectos*/ { GCRY_CIPHER_AES, 16, NULL, "BBAA99887766554433221100", "", "", "785407BFFFC8AD9EDCC5520AC9111EE6" }, { GCRY_CIPHER_AES, 16, NULL, "BBAA99887766554433221101", "0001020304050607", "0001020304050607", "6820B3657B6F615A5725BDA0D3B4EB3A257C9AF1F8F03009" }, { GCRY_CIPHER_AES, 16, NULL, "BBAA99887766554433221102", "0001020304050607", "", "81017F8203F081277152FADE694A0A00" }, { GCRY_CIPHER_AES, 16, NULL, "BBAA99887766554433221103", "", "0001020304050607", "45DD69F8F5AAE72414054CD1F35D82760B2CD00D2F99BFA9" }, { GCRY_CIPHER_AES, 16, NULL, "BBAA99887766554433221104", "000102030405060708090A0B0C0D0E0F", "000102030405060708090A0B0C0D0E0F", "571D535B60B277188BE5147170A9A22C3AD7A4FF3835B8C5" "701C1CCEC8FC3358" }, { GCRY_CIPHER_AES, 16, NULL, "BBAA99887766554433221105", "000102030405060708090A0B0C0D0E0F", "", "8CF761B6902EF764462AD86498CA6B97" }, { GCRY_CIPHER_AES, 16, NULL, "BBAA99887766554433221106", "", "000102030405060708090A0B0C0D0E0F", "5CE88EC2E0692706A915C00AEB8B2396F40E1C743F52436B" "DF06D8FA1ECA343D" }, { GCRY_CIPHER_AES, 16, NULL, "BBAA99887766554433221107", "000102030405060708090A0B0C0D0E0F1011121314151617", "000102030405060708090A0B0C0D0E0F1011121314151617", "1CA2207308C87C010756104D8840CE1952F09673A448A122" "C92C62241051F57356D7F3C90BB0E07F" }, { GCRY_CIPHER_AES, 16, NULL, "BBAA99887766554433221108", "000102030405060708090A0B0C0D0E0F1011121314151617", "", "6DC225A071FC1B9F7C69F93B0F1E10DE" }, { GCRY_CIPHER_AES, 16, NULL, "BBAA99887766554433221109", "", "000102030405060708090A0B0C0D0E0F1011121314151617", "221BD0DE7FA6FE993ECCD769460A0AF2D6CDED0C395B1C3C" "E725F32494B9F914D85C0B1EB38357FF" }, { GCRY_CIPHER_AES, 16, NULL, "BBAA9988776655443322110A", "000102030405060708090A0B0C0D0E0F1011121314151617" "18191A1B1C1D1E1F", "000102030405060708090A0B0C0D0E0F1011121314151617" "18191A1B1C1D1E1F", "BD6F6C496201C69296C11EFD138A467ABD3C707924B964DE" "AFFC40319AF5A48540FBBA186C5553C68AD9F592A79A4240" }, { GCRY_CIPHER_AES, 16, NULL, "BBAA9988776655443322110B", "000102030405060708090A0B0C0D0E0F1011121314151617" "18191A1B1C1D1E1F", "", "FE80690BEE8A485D11F32965BC9D2A32" }, { GCRY_CIPHER_AES, 16, NULL, "BBAA9988776655443322110C", "", "000102030405060708090A0B0C0D0E0F1011121314151617" "18191A1B1C1D1E1F", "2942BFC773BDA23CABC6ACFD9BFD5835BD300F0973792EF4" "6040C53F1432BCDFB5E1DDE3BC18A5F840B52E653444D5DF" }, { GCRY_CIPHER_AES, 16, NULL, "BBAA9988776655443322110D", "000102030405060708090A0B0C0D0E0F1011121314151617" "18191A1B1C1D1E1F2021222324252627", "000102030405060708090A0B0C0D0E0F1011121314151617" "18191A1B1C1D1E1F2021222324252627", "D5CA91748410C1751FF8A2F618255B68A0A12E093FF45460" "6E59F9C1D0DDC54B65E8628E568BAD7AED07BA06A4A69483" "A7035490C5769E60" }, { GCRY_CIPHER_AES, 16, NULL, "BBAA9988776655443322110E", "000102030405060708090A0B0C0D0E0F1011121314151617" "18191A1B1C1D1E1F2021222324252627", "", "C5CD9D1850C141E358649994EE701B68" }, { GCRY_CIPHER_AES, 16, NULL, "BBAA9988776655443322110F", "", "000102030405060708090A0B0C0D0E0F1011121314151617" "18191A1B1C1D1E1F2021222324252627", "4412923493C57D5DE0D700F753CCE0D1D2D95060122E9F15" "A5DDBFC5787E50B5CC55EE507BCB084E479AD363AC366B95" "A98CA5F3000B1479" }, { GCRY_CIPHER_AES, 12, "0F0E0D0C0B0A09080706050403020100", "BBAA9988776655443322110D", "000102030405060708090A0B0C0D0E0F1011121314151617" "18191A1B1C1D1E1F2021222324252627", "000102030405060708090A0B0C0D0E0F1011121314151617" "18191A1B1C1D1E1F2021222324252627", "1792A4E31E0755FB03E31B22116E6C2DDF9EFD6E33D536F1" "A0124B0A55BAE884ED93481529C76B6AD0C515F4D1CDD4FD" "AC4F02AA" } }; gpg_error_t err = 0; gcry_cipher_hd_t hde, hdd; unsigned char out[MAX_DATA_LEN]; unsigned char tag[16]; int tidx; if (verbose) fprintf (stderr, " Starting OCB checks.\n"); for (tidx = 0; tidx < DIM (tv); tidx++) { char *key, *nonce, *aad, *ciph, *plain; size_t keylen, noncelen, aadlen, ciphlen, plainlen; int taglen; size_t taglen2; if (verbose) fprintf (stderr, " checking OCB mode for %s [%i] (tv %d)\n", gcry_cipher_algo_name (tv[tidx].algo), tv[tidx].algo, tidx); /* Convert to hex strings to binary. */ key = hex2buffer (tv[tidx].key? tv[tidx].key /* */: "000102030405060708090A0B0C0D0E0F", &keylen); nonce = hex2buffer (tv[tidx].nonce, &noncelen); aad = hex2buffer (tv[tidx].aad, &aadlen); plain = hex2buffer (tv[tidx].plain, &plainlen); ciph = hex2buffer (tv[tidx].ciph, &ciphlen); /* Check that our test vectors are sane. */ assert (plainlen <= sizeof out); assert (tv[tidx].taglen <= ciphlen); assert (tv[tidx].taglen <= sizeof tag); err = gcry_cipher_open (&hde, tv[tidx].algo, GCRY_CIPHER_MODE_OCB, 0); if (!err) err = gcry_cipher_open (&hdd, tv[tidx].algo, GCRY_CIPHER_MODE_OCB, 0); if (err) { fail ("cipher-ocb, gcry_cipher_open failed (tv %d): %s\n", tidx, gpg_strerror (err)); return; } /* Set the taglen. For the first handle we do this only for a non-default taglen. For the second handle we check that we can also set to the default taglen. */ taglen = tv[tidx].taglen; if (taglen != 16) { err = gcry_cipher_ctl (hde, GCRYCTL_SET_TAGLEN, &taglen, sizeof taglen); if (err) { fail ("cipher-ocb, gcryctl_set_taglen failed (tv %d): %s\n", tidx, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } } err = gcry_cipher_ctl (hdd, GCRYCTL_SET_TAGLEN, &taglen, sizeof taglen); if (err) { fail ("cipher-ocb, gcryctl_set_taglen failed (tv %d): %s\n", tidx, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } err = gcry_cipher_info (hde, GCRYCTL_GET_TAGLEN, NULL, &taglen2); if (err) { fail ("cipher-ocb, gcryctl_get_taglen failed (tv %d): %s\n", tidx, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } if (taglen2 != tv[tidx].taglen) { fail ("cipher-ocb, gcryctl_get_taglen returned bad length (tv %d): " "got=%zu want=%d\n", tidx, taglen2, tv[tidx].taglen); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } err = gcry_cipher_setkey (hde, key, keylen); if (!err) err = gcry_cipher_setkey (hdd, key, keylen); if (err) { fail ("cipher-ocb, gcry_cipher_setkey failed (tv %d): %s\n", tidx, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } err = gcry_cipher_setiv (hde, nonce, noncelen); if (!err) err = gcry_cipher_setiv (hdd, nonce, noncelen); if (err) { fail ("cipher-ocb, gcry_cipher_setiv failed (tv %d): %s\n", tidx, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } err = gcry_cipher_authenticate (hde, aad, aadlen); if (err) { fail ("cipher-ocb, gcry_cipher_authenticate failed (tv %d): %s\n", tidx, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } err = gcry_cipher_final (hde); if (!err) { if (inplace) { memcpy(out, plain, plainlen); err = gcry_cipher_encrypt (hde, out, plainlen, NULL, 0); } else { err = gcry_cipher_encrypt (hde, out, MAX_DATA_LEN, plain, plainlen); } } if (err) { fail ("cipher-ocb, gcry_cipher_encrypt failed (tv %d): %s\n", tidx, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } /* Check that the encrypt output matches the expected cipher text without the tag (i.e. at the length of plaintext). */ if (memcmp (ciph, out, plainlen)) { mismatch (ciph, plainlen, out, plainlen); fail ("cipher-ocb, encrypt data mismatch (tv %d)\n", tidx); } /* Check that the tag matches TAGLEN bytes from the end of the expected ciphertext. */ err = gcry_cipher_gettag (hde, tag, tv[tidx].taglen); if (err) { fail ("cipher_ocb, gcry_cipher_gettag failed (tv %d): %s\n", tidx, gpg_strerror (err)); } if (memcmp (ciph + ciphlen - tv[tidx].taglen, tag, tv[tidx].taglen)) { mismatch (ciph + ciphlen - tv[tidx].taglen, tv[tidx].taglen, tag, tv[tidx].taglen); fail ("cipher-ocb, encrypt tag mismatch (tv %d)\n", tidx); } err = gcry_cipher_authenticate (hdd, aad, aadlen); if (err) { fail ("cipher-ocb, gcry_cipher_authenticate failed (tv %d): %s\n", tidx, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } /* Now for the decryption. */ err = gcry_cipher_final (hdd); if (!err) { if (inplace) { err = gcry_cipher_decrypt (hdd, out, plainlen, NULL, 0); } else { unsigned char tmp[MAX_DATA_LEN]; memcpy(tmp, out, plainlen); err = gcry_cipher_decrypt (hdd, out, plainlen, tmp, plainlen); } } if (err) { fail ("cipher-ocb, gcry_cipher_decrypt (tv %d) failed: %s\n", tidx, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } /* We still have TAG from the encryption. */ err = gcry_cipher_checktag (hdd, tag, tv[tidx].taglen); if (err) { fail ("cipher-ocb, gcry_cipher_checktag failed (tv %d): %s\n", tidx, gpg_strerror (err)); } /* Check that the decrypt output matches the original plaintext. */ if (memcmp (plain, out, plainlen)) { mismatch (plain, plainlen, out, plainlen); fail ("cipher-ocb, decrypt data mismatch (tv %d)\n", tidx); } /* Check that gettag also works for decryption. */ err = gcry_cipher_gettag (hdd, tag, tv[tidx].taglen); if (err) { fail ("cipher_ocb, decrypt gettag failed (tv %d): %s\n", tidx, gpg_strerror (err)); } if (memcmp (ciph + ciphlen - tv[tidx].taglen, tag, tv[tidx].taglen)) { mismatch (ciph + ciphlen - tv[tidx].taglen, tv[tidx].taglen, tag, tv[tidx].taglen); fail ("cipher-ocb, decrypt tag mismatch (tv %d)\n", tidx); } gcry_cipher_close (hde); gcry_cipher_close (hdd); xfree (nonce); xfree (aad); xfree (ciph); xfree (plain); xfree (key); } if (verbose) fprintf (stderr, " Completed OCB checks.\n"); } static void check_ocb_cipher_largebuf_split (int algo, int keylen, const char *tagexpect, unsigned int splitpos) { static const unsigned char key[32] = "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F" "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F"; static const unsigned char nonce[12] = "\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x00\x01\x02\x03"; const size_t buflen = 1024 * 1024 * 2 + 32; unsigned char *inbuf; unsigned char *outbuf; gpg_error_t err = 0; gcry_cipher_hd_t hde, hdd; unsigned char tag[16]; int i; inbuf = xmalloc(buflen); if (!inbuf) { fail ("out-of-memory\n"); return; } outbuf = xmalloc(buflen); if (!outbuf) { fail ("out-of-memory\n"); xfree(inbuf); return; } for (i = 0; i < buflen; i++) inbuf[i] = 'a'; err = gcry_cipher_open (&hde, algo, GCRY_CIPHER_MODE_OCB, 0); if (!err) err = gcry_cipher_open (&hdd, algo, GCRY_CIPHER_MODE_OCB, 0); if (err) { fail ("cipher-ocb, gcry_cipher_open failed (large, algo %d): %s\n", algo, gpg_strerror (err)); goto out_free; } err = gcry_cipher_setkey (hde, key, keylen); if (!err) err = gcry_cipher_setkey (hdd, key, keylen); if (err) { fail ("cipher-ocb, gcry_cipher_setkey failed (large, algo %d): %s\n", algo, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); goto out_free; } err = gcry_cipher_setiv (hde, nonce, 12); if (!err) err = gcry_cipher_setiv (hdd, nonce, 12); if (err) { fail ("cipher-ocb, gcry_cipher_setiv failed (large, algo %d): %s\n", algo, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); goto out_free; } if (splitpos) { err = gcry_cipher_authenticate (hde, inbuf, splitpos); } if (!err) { err = gcry_cipher_authenticate (hde, inbuf + splitpos, buflen - splitpos); } if (err) { fail ("cipher-ocb, gcry_cipher_authenticate failed (large, algo %d): %s\n", algo, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); goto out_free; } if (splitpos) { err = gcry_cipher_encrypt (hde, outbuf, splitpos, inbuf, splitpos); } if (!err) { err = gcry_cipher_final (hde); if (!err) { err = gcry_cipher_encrypt (hde, outbuf + splitpos, buflen - splitpos, inbuf + splitpos, buflen - splitpos); } } if (err) { fail ("cipher-ocb, gcry_cipher_encrypt failed (large, algo %d): %s\n", algo, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); goto out_free; } /* Check that the tag matches. */ err = gcry_cipher_gettag (hde, tag, 16); if (err) { fail ("cipher_ocb, gcry_cipher_gettag failed (large, algo %d): %s\n", algo, gpg_strerror (err)); } if (memcmp (tagexpect, tag, 16)) { mismatch (tagexpect, 16, tag, 16); fail ("cipher-ocb, encrypt tag mismatch (large, algo %d)\n", algo); } err = gcry_cipher_authenticate (hdd, inbuf, buflen); if (err) { fail ("cipher-ocb, gcry_cipher_authenticate failed (large, algo %d): %s\n", algo, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); goto out_free; } /* Now for the decryption. */ if (splitpos) { err = gcry_cipher_decrypt (hdd, outbuf, splitpos, NULL, 0); } if (!err) { err = gcry_cipher_final (hdd); if (!err) { err = gcry_cipher_decrypt (hdd, outbuf + splitpos, buflen - splitpos, NULL, 0); } } if (err) { fail ("cipher-ocb, gcry_cipher_decrypt (large, algo %d) failed: %s\n", algo, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); goto out_free; } /* We still have TAG from the encryption. */ err = gcry_cipher_checktag (hdd, tag, 16); if (err) { fail ("cipher-ocb, gcry_cipher_checktag failed (large, algo %d): %s\n", algo, gpg_strerror (err)); } /* Check that the decrypt output matches the original plaintext. */ if (memcmp (inbuf, outbuf, buflen)) { /*mismatch (inbuf, buflen, outbuf, buflen);*/ fail ("cipher-ocb, decrypt data mismatch (large, algo %d)\n", algo); } /* Check that gettag also works for decryption. */ err = gcry_cipher_gettag (hdd, tag, 16); if (err) { fail ("cipher_ocb, decrypt gettag failed (large, algo %d): %s\n", algo, gpg_strerror (err)); } if (memcmp (tagexpect, tag, 16)) { mismatch (tagexpect, 16, tag, 16); fail ("cipher-ocb, decrypt tag mismatch (large, algo %d)\n", algo); } gcry_cipher_close (hde); gcry_cipher_close (hdd); out_free: xfree(outbuf); xfree(inbuf); } static void check_ocb_cipher_largebuf (int algo, int keylen, const char *tagexpect) { unsigned int split; for (split = 0; split < 32 * 16; split = split * 2 + 16) { check_ocb_cipher_largebuf_split(algo, keylen, tagexpect, split); } } static void check_ocb_cipher_splitaad (void) { const char t_nonce[] = ("BBAA9988776655443322110D"); const char t_plain[] = ("000102030405060708090A0B0C0D0E0F1011121314151617" "18191A1B1C1D1E1F2021222324252627"); const char t_ciph[] = ("D5CA91748410C1751FF8A2F618255B68A0A12E093FF45460" "6E59F9C1D0DDC54B65E8628E568BAD7AED07BA06A4A69483" "A7035490C5769E60"); struct { const char *aad0; const char *aad1; const char *aad2; const char *aad3; } tv[] = { { "000102030405060708090A0B0C0D0E0F" "101112131415161718191A1B1C1D1E1F2021222324252627" }, { "000102030405060708090A0B0C0D0E0F", "101112131415161718191A1B1C1D1E1F", "2021222324252627" }, { "000102030405060708090A0B0C0D0E0F", "1011121314151617", "18191A1B1C1D1E1F", "2021222324252627" }, { "000102030405060708090A0B0C0D0E0F", "101112131415161718191A1B1C1D1E1F", "20", "21222324252627" }, { "000102030405060708090A0B0C0D0E0F", "101112131415161718191A1B1C1D1E1F", "2021", "222324252627" }, { "000102030405060708090A0B0C0D0E0F", "101112131415161718191A1B1C1D1E1F", "202122", "2324252627" }, { "000102030405060708090A0B0C0D0E0F", "101112131415161718191A1B1C1D1E1F", "20212223", "24252627" }, { "000102030405060708090A0B0C0D0E0F", "101112131415161718191A1B1C1D1E1F", "2021222324", "252627" }, { "000102030405060708090A0B0C0D0E0F", "101112131415161718191A1B1C1D1E1F", "202122232425", "2627" }, { "000102030405060708090A0B0C0D0E0F", "101112131415161718191A1B1C1D1E1F", "20212223242526" "27" }, { "000102030405060708090A0B0C0D0E0F", "1011121314151617", "18191A1B1C1D1E1F2021222324252627" }, { "00", "0102030405060708090A0B0C0D0E0F", "1011121314151617", "18191A1B1C1D1E1F2021222324252627" }, { "0001", "02030405060708090A0B0C0D0E0F", "1011121314151617", "18191A1B1C1D1E1F2021222324252627" }, { "000102030405060708090A0B0C0D", "0E0F", "1011121314151617", "18191A1B1C1D1E1F2021222324252627" }, { "000102030405060708090A0B0C0D0E", "0F", "1011121314151617", "18191A1B1C1D1E1F2021222324252627" }, { "000102030405060708090A0B0C0D0E", "0F101112131415161718191A1B1C1D1E1F20212223242526", "27" } }; gpg_error_t err = 0; gcry_cipher_hd_t hde; unsigned char out[MAX_DATA_LEN]; unsigned char tag[16]; int tidx; char *key, *nonce, *ciph, *plain; size_t keylen, noncelen, ciphlen, plainlen; int i; /* Convert to hex strings to binary. */ key = hex2buffer ("000102030405060708090A0B0C0D0E0F", &keylen); nonce = hex2buffer (t_nonce, &noncelen); plain = hex2buffer (t_plain, &plainlen); ciph = hex2buffer (t_ciph, &ciphlen); /* Check that our test vectors are sane. */ assert (plainlen <= sizeof out); assert (16 <= ciphlen); assert (16 <= sizeof tag); for (tidx = 0; tidx < DIM (tv); tidx++) { char *aad[4]; size_t aadlen[4]; if (verbose) fprintf (stderr, " checking OCB aad split (tv %d)\n", tidx); aad[0] = tv[tidx].aad0? hex2buffer (tv[tidx].aad0, aadlen+0) : NULL; aad[1] = tv[tidx].aad1? hex2buffer (tv[tidx].aad1, aadlen+1) : NULL; aad[2] = tv[tidx].aad2? hex2buffer (tv[tidx].aad2, aadlen+2) : NULL; aad[3] = tv[tidx].aad3? hex2buffer (tv[tidx].aad3, aadlen+3) : NULL; err = gcry_cipher_open (&hde, GCRY_CIPHER_AES, GCRY_CIPHER_MODE_OCB, 0); if (err) { fail ("cipher-ocb-splitadd, gcry_cipher_open failed: %s\n", gpg_strerror (err)); return; } err = gcry_cipher_setkey (hde, key, keylen); if (err) { fail ("cipher-ocb-splitaad, gcry_cipher_setkey failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hde); return; } err = gcry_cipher_setiv (hde, nonce, noncelen); if (err) { fail ("cipher-ocb-splitaad, gcry_cipher_setiv failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hde); return; } for (i=0; i < DIM (aad); i++) { if (!aad[i]) continue; err = gcry_cipher_authenticate (hde, aad[i], aadlen[i]); if (err) { fail ("cipher-ocb-splitaad," " gcry_cipher_authenticate failed (tv=%d,i=%d): %s\n", tidx, i, gpg_strerror (err)); gcry_cipher_close (hde); return; } } err = gcry_cipher_final (hde); if (!err) err = gcry_cipher_encrypt (hde, out, MAX_DATA_LEN, plain, plainlen); if (err) { fail ("cipher-ocb-splitaad, gcry_cipher_encrypt failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hde); return; } /* Check that the encrypt output matches the expected cipher text without the tag (i.e. at the length of plaintext). */ if (memcmp (ciph, out, plainlen)) { mismatch (ciph, plainlen, out, plainlen); fail ("cipher-ocb-splitaad, encrypt data mismatch\n"); } /* Check that the tag matches TAGLEN bytes from the end of the expected ciphertext. */ err = gcry_cipher_gettag (hde, tag, 16); if (err) { fail ("cipher-ocb-splitaad, gcry_cipher_gettag failed: %s\n", gpg_strerror (err)); } if (memcmp (ciph + ciphlen - 16, tag, 16)) { mismatch (ciph + ciphlen - 16, 16, tag, 16); fail ("cipher-ocb-splitaad, encrypt tag mismatch\n"); } gcry_cipher_close (hde); xfree (aad[0]); xfree (aad[1]); xfree (aad[2]); xfree (aad[3]); } xfree (nonce); xfree (ciph); xfree (plain); xfree (key); } static void check_ocb_cipher (void) { /* Check OCB cipher with separate destination and source buffers for * encryption/decryption. */ do_check_ocb_cipher(0); /* Check OCB cipher with inplace encrypt/decrypt. */ do_check_ocb_cipher(1); /* Check large buffer encryption/decryption. */ check_ocb_cipher_largebuf(GCRY_CIPHER_AES, 16, "\xf5\xf3\x12\x7d\x58\x2d\x96\xe8" "\x33\xfd\x7a\x4f\x42\x60\x5d\x20"); check_ocb_cipher_largebuf(GCRY_CIPHER_AES256, 32, "\xfa\x26\xa5\xbf\xf6\x7d\x3a\x8d" "\xfe\x96\x67\xc9\xc8\x41\x03\x51"); check_ocb_cipher_largebuf(GCRY_CIPHER_CAMELLIA128, 16, "\x28\x23\x38\x45\x2b\xfd\x42\x45" "\x43\x64\x7e\x67\x7f\xf4\x8b\xcd"); check_ocb_cipher_largebuf(GCRY_CIPHER_CAMELLIA192, 24, "\xee\xca\xe5\x39\x27\x2d\x33\xe7" "\x79\x74\xb0\x1d\x37\x12\xd5\x6c"); check_ocb_cipher_largebuf(GCRY_CIPHER_CAMELLIA256, 32, "\x39\x39\xd0\x2d\x05\x68\x74\xee" "\x18\x6b\xea\x3d\x0b\xd3\x58\xae"); check_ocb_cipher_largebuf(GCRY_CIPHER_TWOFISH, 16, "\x63\xe3\x0e\xb9\x11\x6f\x14\xba" "\x79\xe4\xa7\x9e\xad\x3c\x02\x0c"); check_ocb_cipher_largebuf(GCRY_CIPHER_TWOFISH, 32, "\xf6\xd4\xfe\x4e\x50\x85\x13\x59" "\x69\x0e\x4c\x67\x3e\xdd\x47\x90"); check_ocb_cipher_largebuf(GCRY_CIPHER_SERPENT128, 16, "\x3c\xfb\x66\x14\x3c\xc8\x6c\x67" "\x26\xb8\x23\xeb\xaf\x43\x98\x69"); check_ocb_cipher_largebuf(GCRY_CIPHER_SERPENT192, 24, "\x5e\x62\x27\xc5\x32\xc3\x1d\xe6" "\x2e\x65\xe7\xd6\xfb\x05\xd7\xb2"); check_ocb_cipher_largebuf(GCRY_CIPHER_SERPENT256, 32, "\xe7\x8b\xe6\xd4\x2f\x7a\x36\x4c" "\xba\xee\x20\xe2\x68\xf4\xcb\xcc"); /* Check that the AAD data is correctly buffered. */ check_ocb_cipher_splitaad (); } static void do_check_xts_cipher (int inplace) { /* Note that we use hex strings and not binary strings in TV. That makes it easier to maintain the test vectors. */ static const struct { int algo; const char *key; /* NULL means "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F" */ const char *iv; const char *plain; const char *ciph; } tv[] = { /* CAVS; hex/XTSGenAES128.rsp; COUNT=100 */ { GCRY_CIPHER_AES, "bcb6613c495de4bdad9c19f04e4b3915f9ecb379e1a575b633337e934fca1050", "64981173159d58ac355a20120c8e81f1", "189acacee06dfa7c94484c7dae59e166", "7900191d0f19a97668fdba9def84eedc" }, /* CAVS; hex/XTSGenAES128.rsp; COUNT=101 */ { GCRY_CIPHER_AES, "b7b93f516aef295eff3a29d837cf1f135347e8a21dae616ff5062b2e8d78ce5e", "873edea653b643bd8bcf51403197ed14", "236f8a5b58dd55f6194ed70c4ac1a17f1fe60ec9a6c454d087ccb77d6b638c47", "22e6a3c6379dcf7599b052b5a749c7f78ad8a11b9f1aa9430cf3aef445682e19" }, /* CAVS; hex/XTSGenAES128.rsp; COUNT=301 */ { GCRY_CIPHER_AES, "394c97881abd989d29c703e48a72b397a7acf51b59649eeea9b33274d8541df4", "4b15c684a152d485fe9937d39b168c29", "2f3b9dcfbae729583b1d1ffdd16bb6fe2757329435662a78f0", "f3473802e38a3ffef4d4fb8e6aa266ebde553a64528a06463e" }, /* CAVS; hex/XTSGenAES128.rsp; COUNT=500 */ { GCRY_CIPHER_AES, "783a83ec52a27405dff9de4c57f9c979b360b6a5df88d67ec1a052e6f582a717", "886e975b29bdf6f0c01bb47f61f6f0f5", "b04d84da856b9a59ce2d626746f689a8051dacd6bce3b990aa901e4030648879", "f941039ebab8cac39d59247cbbcb4d816c726daed11577692c55e4ac6d3e6820" }, /* CAVS; hex/XTSGenAES256.rsp; COUNT=1 */ { GCRY_CIPHER_AES256, "1ea661c58d943a0e4801e42f4b0947149e7f9f8e3e68d0c7505210bd311a0e7c" "d6e13ffdf2418d8d1911c004cda58da3d619b7e2b9141e58318eea392cf41b08", "adf8d92627464ad2f0428e84a9f87564", "2eedea52cd8215e1acc647e810bbc3642e87287f8d2e57e36c0a24fbc12a202e", "cbaad0e2f6cea3f50b37f934d46a9b130b9d54f07e34f36af793e86f73c6d7db" }, /* CAVS; hex/XTSGenAES256.rsp; COUNT=101 */ { GCRY_CIPHER_AES256, "266c336b3b01489f3267f52835fd92f674374b88b4e1ebd2d36a5f457581d9d0" "42c3eef7b0b7e5137b086496b4d9e6ac658d7196a23f23f036172fdb8faee527", "06b209a7a22f486ecbfadb0f3137ba42", "ca7d65ef8d3dfad345b61ccddca1ad81de830b9e86c7b426d76cb7db766852d9" "81c6b21409399d78f42cc0b33a7bbb06", "c73256870cc2f4dd57acc74b5456dbd776912a128bc1f77d72cdebbf270044b7" "a43ceed29025e1e8be211fa3c3ed002d" }, /* CAVS; hex/XTSGenAES256.rsp; COUNT=401 */ { GCRY_CIPHER_AES256, "33e89e817ff8d037d6ac5a2296657503f20885d94c483e26449066bd9284d130" "2dbdbb4b66b6b9f4687f13dd028eb6aa528ca91deb9c5f40db93218806033801", "a78c04335ab7498a52b81ed74b48e6cf", "14c3ac31291b075f40788247c3019e88c7b40bac3832da45bbc6c4fe7461371b" "4dfffb63f71c9f8edb98f28ff4f33121", "dead7e587519bc78c70d99279fbe3d9b1ad13cdaae69824e0ab8135413230bfd" "b13babe8f986fbb30d46ab5ec56b916e" }, /* From https://github.com/heisencoder/XTS-AES/blob/master/testvals/ */ { GCRY_CIPHER_AES, "fffefdfcfbfaf9f8f7f6f5f4f3f2f1f0fffefdfcfbfaf9f8f7f6f5f4f3f2f1f0", "9a785634120000000000000000000000", "000102030405060708090a0b0c0d0e0f10", "7fb2e8beccbb5c118aa52ddca31220bb1b" }, { GCRY_CIPHER_AES, "fffefdfcfbfaf9f8f7f6f5f4f3f2f1f0bfbebdbcbbbab9b8b7b6b5b4b3b2b1b0", "9a785634120000000000000000000000", "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e", "d05bc090a8e04f1b3d3ecdd5baec0fd4edbf9dace45d6f6a7306e64be5dd82" }, { GCRY_CIPHER_AES, "2718281828459045235360287471352631415926535897932384626433832795", "00000000000000000000000000000000", "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F" "20212223", "27A7479BEFA1D476489F308CD4CFA6E288F548E5C4239F91712A587E2B05AC3D" "A96E4BBE" }, { GCRY_CIPHER_AES256, "2718281828459045235360287471352662497757247093699959574966967627" "3141592653589793238462643383279502884197169399375105820974944592", "11000000000000000000000000000000", "3A060A8CAD115A6F44572E3759E43C8F8832FEDC28A8E35B357B5CF3EDBEF788" "CAD8BFCB23", "6D1C78A8BAD91DB2924C507CCEDE835F5BADD157DA0AF55C98BBC28CF676F9FA" "61618FA696" }, { GCRY_CIPHER_AES256, "2718281828459045235360287471352662497757247093699959574966967627" "3141592653589793238462643383279502884197169399375105820974944592", "11000000000000000000000000000000", "3A060A8CAD115A6F44572E3759E43C8F8832FEDC28A8E35B357B5CF3EDBEF788" "CAD8BFCB23", "6D1C78A8BAD91DB2924C507CCEDE835F5BADD157DA0AF55C98BBC28CF676F9FA" "61618FA696" }, { GCRY_CIPHER_AES, "e0e1e2e3e4e5e6e7e8e9eaebecedeeefc0c1c2c3c4c5c6c7c8c9cacbcccdcecf", "21436587a90000000000000000000000", "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" "202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f" "404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f" "606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f" "808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f" "a0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebf" "c0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedf" "e0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff" "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" "202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f" "404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f" "606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f" "808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f" "a0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebf" "c0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedf" "e0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff" "0001020304050607", "38b45812ef43a05bd957e545907e223b954ab4aaf088303ad910eadf14b42be6" "8b2461149d8c8ba85f992be970bc621f1b06573f63e867bf5875acafa04e42cc" "bd7bd3c2a0fb1fff791ec5ec36c66ae4ac1e806d81fbf709dbe29e471fad3854" "9c8e66f5345d7c1eb94f405d1ec785cc6f6a68f6254dd8339f9d84057e01a177" "41990482999516b5611a38f41bb6478e6f173f320805dd71b1932fc333cb9ee3" "9936beea9ad96fa10fb4112b901734ddad40bc1878995f8e11aee7d141a2f5d4" "8b7a4e1e7f0b2c04830e69a4fd1378411c2f287edf48c6c4e5c247a19680f7fe" "41cefbd49b582106e3616cbbe4dfb2344b2ae9519391f3e0fb4922254b1d6d2d" "19c6d4d537b3a26f3bcc51588b32f3eca0829b6a5ac72578fb814fb43cf80d64" "a233e3f997a3f02683342f2b33d25b492536b93becb2f5e1a8b82f5b88334272" "9e8ae09d16938841a21a97fb543eea3bbff59f13c1a18449e398701c1ad51648" "346cbc04c27bb2da3b93a1372ccae548fb53bee476f9e9c91773b1bb19828394" "d55d3e1a20ed69113a860b6829ffa847224604435070221b257e8dff783615d2" "cae4803a93aa4334ab482a0afac9c0aeda70b45a481df5dec5df8cc0f423c77a" "5fd46cd312021d4b438862419a791be03bb4d97c0e59578542531ba466a83baf" "92cefc151b5cc1611a167893819b63fb37ec662bc0fc907db74a94468a55a7bc" "8a6b18e86de60290" }, { GCRY_CIPHER_AES256, "2718281828459045235360287471352662497757247093699959574966967627" "3141592653589793238462643383279502884197169399375105820974944592", "ffffffff000000000000000000000000", "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" "202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f" "404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f" "606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f" "808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f" "a0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebf" "c0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedf" "e0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff" "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" "202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f" "404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f" "606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f" "808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f" "a0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebf" "c0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedf" "e0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff", "bf53d2dade78e822a4d949a9bc6766b01b06a8ef70d26748c6a7fc36d80ae4c5" "520f7c4ab0ac8544424fa405162fef5a6b7f229498063618d39f0003cb5fb8d1" "c86b643497da1ff945c8d3bedeca4f479702a7a735f043ddb1d6aaade3c4a0ac" "7ca7f3fa5279bef56f82cd7a2f38672e824814e10700300a055e1630b8f1cb0e" "919f5e942010a416e2bf48cb46993d3cb6a51c19bacf864785a00bc2ecff15d3" "50875b246ed53e68be6f55bd7e05cfc2b2ed6432198a6444b6d8c247fab941f5" "69768b5c429366f1d3f00f0345b96123d56204c01c63b22ce78baf116e525ed9" "0fdea39fa469494d3866c31e05f295ff21fea8d4e6e13d67e47ce722e9698a1c" "1048d68ebcde76b86fcf976eab8aa9790268b7068e017a8b9b749409514f1053" "027fd16c3786ea1bac5f15cb79711ee2abe82f5cf8b13ae73030ef5b9e4457e7" "5d1304f988d62dd6fc4b94ed38ba831da4b7634971b6cd8ec325d9c61c00f1df" "73627ed3745a5e8489f3a95c69639c32cd6e1d537a85f75cc844726e8a72fc00" "77ad22000f1d5078f6b866318c668f1ad03d5a5fced5219f2eabbd0aa5c0f460" "d183f04404a0d6f469558e81fab24a167905ab4c7878502ad3e38fdbe62a4155" "6cec37325759533ce8f25f367c87bb5578d667ae93f9e2fd99bcbc5f2fbba88c" "f6516139420fcff3b7361d86322c4bd84c82f335abb152c4a93411373aaa8220" } }; gpg_error_t err = 0; gcry_cipher_hd_t hde, hdd; int tidx; int got_err = 0; if (verbose) fprintf (stderr, " Starting XTS checks.\n"); for (tidx = 0; !got_err && tidx < DIM (tv); tidx++) { const char *hexkey = tv[tidx].key; char *key, *iv, *ciph, *plain, *out; size_t keylen, ivlen, ciphlen, plainlen, outlen; if (verbose) fprintf (stderr, " checking XTS mode for %s [%i] (tv %d)\n", gcry_cipher_algo_name (tv[tidx].algo), tv[tidx].algo, tidx); if (!hexkey) hexkey = "000102030405060708090A0B0C0D0E0F" "101112131415161718191A1B1C1D1E1F"; /* Convert to hex strings to binary. */ key = hex2buffer (hexkey, &keylen); iv = hex2buffer (tv[tidx].iv, &ivlen); plain = hex2buffer (tv[tidx].plain, &plainlen); ciph = hex2buffer (tv[tidx].ciph, &ciphlen); outlen = plainlen + 5; out = xmalloc (outlen); assert (plainlen == ciphlen); assert (plainlen <= outlen); assert (out); err = gcry_cipher_open (&hde, tv[tidx].algo, GCRY_CIPHER_MODE_XTS, 0); if (!err) err = gcry_cipher_open (&hdd, tv[tidx].algo, GCRY_CIPHER_MODE_XTS, 0); if (err) { fail ("cipher-xts, gcry_cipher_open failed (tv %d): %s\n", tidx, gpg_strerror (err)); return; } err = gcry_cipher_setkey (hde, key, keylen); if (err && in_fips_mode && memcmp(key, key + keylen/2, keylen/2) == 0) { /* Since both halves of key are the same, fail to set key in FIPS mode is expected. */ goto next_tv; } if (!err) err = gcry_cipher_setkey (hdd, key, keylen); if (err) { fail ("cipher-xts, gcry_cipher_setkey failed (tv %d): %s\n", tidx, gpg_strerror (err)); goto err_out; } err = gcry_cipher_setiv (hde, iv, ivlen); if (!err) err = gcry_cipher_setiv (hdd, iv, ivlen); if (err) { fail ("cipher-xts, gcry_cipher_setiv failed (tv %d): %s\n", tidx, gpg_strerror (err)); goto err_out; } if (inplace) { memcpy(out, plain, plainlen); err = gcry_cipher_encrypt (hde, out, plainlen, NULL, 0); } else { err = gcry_cipher_encrypt (hde, out, outlen, plain, plainlen); } if (err) { fail ("cipher-xts, gcry_cipher_encrypt failed (tv %d): %s\n", tidx, gpg_strerror (err)); goto err_out; } /* Check that the encrypt output matches the expected cipher text. */ if (memcmp (ciph, out, plainlen)) { mismatch (ciph, plainlen, out, plainlen); fail ("cipher-xts, encrypt data mismatch (tv %d)\n", tidx); } /* Now for the decryption. */ if (inplace) { err = gcry_cipher_decrypt (hdd, out, plainlen, NULL, 0); } else { memcpy(ciph, out, ciphlen); err = gcry_cipher_decrypt (hdd, out, plainlen, ciph, ciphlen); } if (err) { fail ("cipher-xts, gcry_cipher_decrypt (tv %d) failed: %s\n", tidx, gpg_strerror (err)); goto err_out; } /* Check that the decrypt output matches the expected plain text. */ if (memcmp (plain, out, plainlen)) { mismatch (plain, plainlen, out, plainlen); fail ("cipher-xts, decrypt data mismatch (tv %d)\n", tidx); } if (0) { err_out: got_err = 1; } next_tv: gcry_cipher_close (hde); gcry_cipher_close (hdd); xfree (iv); xfree (ciph); xfree (plain); xfree (key); xfree (out); } if (verbose) fprintf (stderr, " Completed XTS checks.\n"); } static void check_xts_cipher (void) { /* Check XTS cipher with separate destination and source buffers for * encryption/decryption. */ do_check_xts_cipher(0); /* Check XTS cipher with inplace encrypt/decrypt. */ do_check_xts_cipher(1); } static void check_gost28147_cipher (void) { #if USE_GOST28147 static const struct { char key[MAX_DATA_LEN]; const char *oid; unsigned char plaintext[MAX_DATA_LEN]; int inlen; char out[MAX_DATA_LEN]; } tv[] = { { "\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x80" "\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xd0", "1.2.643.7.1.2.5.1.1", "\x01\x02\x03\x04\x05\x06\x07\x08", 8, "\xce\x5a\x5e\xd7\xe0\x57\x7a\x5f", }, { "\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x80" "\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xd0", "1.2.643.2.2.31.0", "\x01\x02\x03\x04\x05\x06\x07\x08", 8, "\x98\x56\xcf\x8b\xfc\xc2\x82\xf4", }, { "\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x80" "\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xd0", "1.2.643.2.2.31.1", "\x01\x02\x03\x04\x05\x06\x07\x08", 8, "\x66\x81\x84\xae\xdc\x48\xc9\x17", }, { "\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x80" "\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xd0", "1.2.643.2.2.31.2", "\x01\x02\x03\x04\x05\x06\x07\x08", 8, "\xdb\xee\x81\x14\x7b\x74\xb0\xf2", }, { "\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x80" "\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xd0", "1.2.643.2.2.31.3", "\x01\x02\x03\x04\x05\x06\x07\x08", 8, "\x31\xa3\x85\x9d\x0a\xee\xb8\x0e", }, { "\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x80" "\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xd0", "1.2.643.2.2.31.4", "\x01\x02\x03\x04\x05\x06\x07\x08", 8, "\xb1\x32\x3e\x0b\x21\x73\xcb\xd1", }, { "\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x80" "\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xd0", "1.2.643.2.2.30.0", "\x01\x02\x03\x04\x05\x06\x07\x08", 8, "\xce\xd5\x2a\x7f\xf7\xf2\x60\xd5", }, { "\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x80" "\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xd0", "1.2.643.2.2.30.1", "\x01\x02\x03\x04\x05\x06\x07\x08", 8, "\xe4\x21\x75\xe1\x69\x22\xd0\xa8", } }; gcry_cipher_hd_t hde, hdd; unsigned char out[MAX_DATA_LEN]; int i, keylen; gcry_error_t err = 0; if (verbose) fprintf (stderr, " Starting GOST28147 cipher checks.\n"); keylen = gcry_cipher_get_algo_keylen(GCRY_CIPHER_GOST28147); if (!keylen) { fail ("gost28147, gcry_cipher_get_algo_keylen failed\n"); return; } for (i = 0; i < sizeof (tv) / sizeof (tv[0]); i++) { err = gcry_cipher_open (&hde, GCRY_CIPHER_GOST28147, GCRY_CIPHER_MODE_ECB, 0); if (!err) err = gcry_cipher_open (&hdd, GCRY_CIPHER_GOST28147, GCRY_CIPHER_MODE_ECB, 0); if (err) { fail ("gost28147, gcry_cipher_open failed: %s\n", gpg_strerror (err)); return; } err = gcry_cipher_setkey (hde, tv[i].key, keylen); if (!err) err = gcry_cipher_setkey (hdd, tv[i].key, keylen); if (err) { fail ("gost28147, gcry_cipher_setkey failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } err = gcry_cipher_set_sbox (hde, tv[i].oid); if (!err) err = gcry_cipher_set_sbox (hdd, tv[i].oid); if (err) { fail ("gost28147, gcry_cipher_set_sbox failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } err = gcry_cipher_encrypt (hde, out, MAX_DATA_LEN, tv[i].plaintext, tv[i].inlen == -1 ? strlen ((char*)tv[i].plaintext) : tv[i].inlen); if (err) { fail ("gost28147, gcry_cipher_encrypt (%d) failed: %s\n", i, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } if (memcmp (tv[i].out, out, tv[i].inlen)) { fail ("gost28147, encrypt mismatch entry %d\n", i); mismatch (tv[i].out, tv[i].inlen, out, tv[i].inlen); } err = gcry_cipher_decrypt (hdd, out, tv[i].inlen, NULL, 0); if (err) { fail ("gost28147, gcry_cipher_decrypt (%d) failed: %s\n", i, gpg_strerror (err)); gcry_cipher_close (hde); gcry_cipher_close (hdd); return; } if (memcmp (tv[i].plaintext, out, tv[i].inlen)) { fail ("gost28147, decrypt mismatch entry %d\n", i); mismatch (tv[i].plaintext, tv[i].inlen, out, tv[i].inlen); } gcry_cipher_close (hde); gcry_cipher_close (hdd); } #endif } static void check_stream_cipher (void) { static const struct tv { const char *name; int algo; int keylen; int ivlen; const char *key; const char *iv; struct data { int inlen; const char *plaintext; const char *out; } data[MAX_DATA_LEN]; } tv[] = { #ifdef USE_SALSA20 { "Salsa20 128 bit, test 1", GCRY_CIPHER_SALSA20, 16, 8, "\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x00\x00\x00\x00\x00\x00\x00\x00", { { 8, "\x00\x00\x00\x00\x00\x00\x00\x00", "\x4D\xFA\x5E\x48\x1D\xA2\x3E\xA0" } } }, { "Salsa20 128 bit, test 2", GCRY_CIPHER_SALSA20, 16, 8, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x80\x00\x00\x00\x00\x00\x00\x00", { { 8, "\x00\x00\x00\x00\x00\x00\x00\x00", "\xB6\x6C\x1E\x44\x46\xDD\x95\x57" } } }, { "Salsa20 128 bit, test 3", GCRY_CIPHER_SALSA20, 16, 8, "\x00\x53\xA6\xF9\x4C\x9F\xF2\x45\x98\xEB\x3E\x91\xE4\x37\x8A\xDD", "\x0D\x74\xDB\x42\xA9\x10\x77\xDE", { { 8, "\x00\x00\x00\x00\x00\x00\x00\x00", "\x05\xE1\xE7\xBE\xB6\x97\xD9\x99" } } }, { "Salsa20 256 bit, test 1", GCRY_CIPHER_SALSA20, 32, 8, "\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x00\x00\x00\x00\x00\x00\x00\x00", { { 8, "\x00\x00\x00\x00\x00\x00\x00\x00", "\xE3\xBE\x8F\xDD\x8B\xEC\xA2\xE3" } } }, { "Salsa20 256 bit, test 2", GCRY_CIPHER_SALSA20, 32, 8, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x80\x00\x00\x00\x00\x00\x00\x00", { { 8, "\x00\x00\x00\x00\x00\x00\x00\x00", "\x2A\xBA\x3D\xC4\x5B\x49\x47\x00" } } }, { "Salsa20 256 bit, ecrypt verified, set 6, vector 0", GCRY_CIPHER_SALSA20, 32, 8, "\x00\x53\xA6\xF9\x4C\x9F\xF2\x45\x98\xEB\x3E\x91\xE4\x37\x8A\xDD" "\x30\x83\xD6\x29\x7C\xCF\x22\x75\xC8\x1B\x6E\xC1\x14\x67\xBA\x0D", "\x0D\x74\xDB\x42\xA9\x10\x77\xDE", { { 8, "\x00\x00\x00\x00\x00\x00\x00\x00", "\xF5\xFA\xD5\x3F\x79\xF9\xDF\x58" }, { 64, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\xF5\xFA\xD5\x3F\x79\xF9\xDF\x58\xC4\xAE\xA0\xD0\xED\x9A\x96\x01" "\xF2\x78\x11\x2C\xA7\x18\x0D\x56\x5B\x42\x0A\x48\x01\x96\x70\xEA" "\xF2\x4C\xE4\x93\xA8\x62\x63\xF6\x77\xB4\x6A\xCE\x19\x24\x77\x3D" "\x2B\xB2\x55\x71\xE1\xAA\x85\x93\x75\x8F\xC3\x82\xB1\x28\x0B\x71" } } }, { "Salsa20/12 128 bit, test 1", GCRY_CIPHER_SALSA20R12, 16, 8, "\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x00\x00\x00\x00\x00\x00\x00\x00", { { 8, "\x00\x00\x00\x00\x00\x00\x00\x00", "\xFC\x20\x7D\xBF\xC7\x6C\x5E\x17" } } }, { "Salsa20/12 128 bit, test 2", GCRY_CIPHER_SALSA20R12, 16, 8, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x80\x00\x00\x00\x00\x00\x00\x00", { { 8, "\x00\x00\x00\x00\x00\x00\x00\x00", "\x08\x28\x39\x9A\x6F\xEF\x20\xDA" } } }, { "Salsa20/12 128 bit, test 3", GCRY_CIPHER_SALSA20R12, 16, 8, "\x00\x53\xA6\xF9\x4C\x9F\xF2\x45\x98\xEB\x3E\x91\xE4\x37\x8A\xDD", "\x0D\x74\xDB\x42\xA9\x10\x77\xDE", { { 8, "\x00\x00\x00\x00\x00\x00\x00\x00", "\xAD\x9E\x60\xE6\xD2\xA2\x64\xB8" } } }, { "Salsa20/12 256 bit, test 1", GCRY_CIPHER_SALSA20R12, 32, 8, "\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x00\x00\x00\x00\x00\x00\x00\x00", { { 8, "\x00\x00\x00\x00\x00\x00\x00\x00", "\xAF\xE4\x11\xED\x1C\x4E\x07\xE4" } } }, { "Salsa20/12 256 bit, test 2", GCRY_CIPHER_SALSA20R12, 32, 8, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x80\x00\x00\x00\x00\x00\x00\x00", { { 8, "\x00\x00\x00\x00\x00\x00\x00\x00", "\x17\x2C\x51\x92\xCB\x6E\x64\x5B" } } }, { "Salsa20/12 256 bit, ecrypt verified, set 6, vector 0", GCRY_CIPHER_SALSA20R12, 32, 8, "\x00\x53\xA6\xF9\x4C\x9F\xF2\x45\x98\xEB\x3E\x91\xE4\x37\x8A\xDD" "\x30\x83\xD6\x29\x7C\xCF\x22\x75\xC8\x1B\x6E\xC1\x14\x67\xBA\x0D", "\x0D\x74\xDB\x42\xA9\x10\x77\xDE", { { 8, "\x00\x00\x00\x00\x00\x00\x00\x00", "\x52\xE2\x0C\xF8\x77\x5A\xE8\x82" }, { 64, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x52\xE2\x0C\xF8\x77\x5A\xE8\x82\xF2\x00\xC2\x99\x9F\xE4\xBA\x31" "\xA7\xA1\x8F\x1D\x5C\x97\x16\x19\x1D\x12\x31\x75\xE1\x47\xBD\x4E" "\x8C\xA6\xED\x16\x6C\xE0\xFC\x8E\x65\xA5\xCA\x60\x84\x20\xFC\x65" "\x44\xC9\x70\x0A\x0F\x21\x38\xE8\xC1\xA2\x86\xFB\x8C\x1F\xBF\xA0" } } }, #endif /*USE_SALSA20*/ #ifdef USE_CHACHA20 /* From draft-strombergson-chacha-test-vectors-01 */ { "ChaCha20 128 bit, TC1", GCRY_CIPHER_CHACHA20, 16, 8, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x00\x00\x00\x00\x00\x00\x00\x00", { { 8, "\x00\x00\x00\x00\x00\x00\x00\x00", "\x89\x67\x09\x52\x60\x83\x64\xfd" }, { 112, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x89\x67\x09\x52\x60\x83\x64\xfd\x00\xb2\xf9\x09\x36\xf0\x31\xc8" "\xe7\x56\xe1\x5d\xba\x04\xb8\x49\x3d\x00\x42\x92\x59\xb2\x0f\x46" "\xcc\x04\xf1\x11\x24\x6b\x6c\x2c\xe0\x66\xbe\x3b\xfb\x32\xd9\xaa" "\x0f\xdd\xfb\xc1\x21\x23\xd4\xb9\xe4\x4f\x34\xdc\xa0\x5a\x10\x3f" "\x6c\xd1\x35\xc2\x87\x8c\x83\x2b\x58\x96\xb1\x34\xf6\x14\x2a\x9d" "\x4d\x8d\x0d\x8f\x10\x26\xd2\x0a\x0a\x81\x51\x2c\xbc\xe6\xe9\x75" "\x8a\x71\x43\xd0\x21\x97\x80\x22\xa3\x84\x14\x1a\x80\xce\xa3\x06" }, { 128, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x89\x67\x09\x52\x60\x83\x64\xfd\x00\xb2\xf9\x09\x36\xf0\x31\xc8" "\xe7\x56\xe1\x5d\xba\x04\xb8\x49\x3d\x00\x42\x92\x59\xb2\x0f\x46" "\xcc\x04\xf1\x11\x24\x6b\x6c\x2c\xe0\x66\xbe\x3b\xfb\x32\xd9\xaa" "\x0f\xdd\xfb\xc1\x21\x23\xd4\xb9\xe4\x4f\x34\xdc\xa0\x5a\x10\x3f" "\x6c\xd1\x35\xc2\x87\x8c\x83\x2b\x58\x96\xb1\x34\xf6\x14\x2a\x9d" "\x4d\x8d\x0d\x8f\x10\x26\xd2\x0a\x0a\x81\x51\x2c\xbc\xe6\xe9\x75" "\x8a\x71\x43\xd0\x21\x97\x80\x22\xa3\x84\x14\x1a\x80\xce\xa3\x06" "\x2f\x41\xf6\x7a\x75\x2e\x66\xad\x34\x11\x98\x4c\x78\x7e\x30\xad" } } }, { "ChaCha20 256 bit, TC1", GCRY_CIPHER_CHACHA20, 32, 8, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x00\x00\x00\x00\x00\x00\x00\x00", { { 8, "\x00\x00\x00\x00\x00\x00\x00\x00", "\x76\xb8\xe0\xad\xa0\xf1\x3d\x90" }, { 112, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x76\xb8\xe0\xad\xa0\xf1\x3d\x90\x40\x5d\x6a\xe5\x53\x86\xbd\x28" "\xbd\xd2\x19\xb8\xa0\x8d\xed\x1a\xa8\x36\xef\xcc\x8b\x77\x0d\xc7" "\xda\x41\x59\x7c\x51\x57\x48\x8d\x77\x24\xe0\x3f\xb8\xd8\x4a\x37" "\x6a\x43\xb8\xf4\x15\x18\xa1\x1c\xc3\x87\xb6\x69\xb2\xee\x65\x86" "\x9f\x07\xe7\xbe\x55\x51\x38\x7a\x98\xba\x97\x7c\x73\x2d\x08\x0d" "\xcb\x0f\x29\xa0\x48\xe3\x65\x69\x12\xc6\x53\x3e\x32\xee\x7a\xed" "\x29\xb7\x21\x76\x9c\xe6\x4e\x43\xd5\x71\x33\xb0\x74\xd8\x39\xd5" }, { 128, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x76\xb8\xe0\xad\xa0\xf1\x3d\x90\x40\x5d\x6a\xe5\x53\x86\xbd\x28" "\xbd\xd2\x19\xb8\xa0\x8d\xed\x1a\xa8\x36\xef\xcc\x8b\x77\x0d\xc7" "\xda\x41\x59\x7c\x51\x57\x48\x8d\x77\x24\xe0\x3f\xb8\xd8\x4a\x37" "\x6a\x43\xb8\xf4\x15\x18\xa1\x1c\xc3\x87\xb6\x69\xb2\xee\x65\x86" "\x9f\x07\xe7\xbe\x55\x51\x38\x7a\x98\xba\x97\x7c\x73\x2d\x08\x0d" "\xcb\x0f\x29\xa0\x48\xe3\x65\x69\x12\xc6\x53\x3e\x32\xee\x7a\xed" "\x29\xb7\x21\x76\x9c\xe6\x4e\x43\xd5\x71\x33\xb0\x74\xd8\x39\xd5" "\x31\xed\x1f\x28\x51\x0a\xfb\x45\xac\xe1\x0a\x1f\x4b\x79\x4d\x6f" } } }, { "ChaCha20 256 bit, TC2", GCRY_CIPHER_CHACHA20, 32, 8, "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x00\x00\x00\x00\x00\x00\x00\x00", { { 128, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\xc5\xd3\x0a\x7c\xe1\xec\x11\x93\x78\xc8\x4f\x48\x7d\x77\x5a\x85" "\x42\xf1\x3e\xce\x23\x8a\x94\x55\xe8\x22\x9e\x88\x8d\xe8\x5b\xbd" "\x29\xeb\x63\xd0\xa1\x7a\x5b\x99\x9b\x52\xda\x22\xbe\x40\x23\xeb" "\x07\x62\x0a\x54\xf6\xfa\x6a\xd8\x73\x7b\x71\xeb\x04\x64\xda\xc0" "\x10\xf6\x56\xe6\xd1\xfd\x55\x05\x3e\x50\xc4\x87\x5c\x99\x30\xa3" "\x3f\x6d\x02\x63\xbd\x14\xdf\xd6\xab\x8c\x70\x52\x1c\x19\x33\x8b" "\x23\x08\xb9\x5c\xf8\xd0\xbb\x7d\x20\x2d\x21\x02\x78\x0e\xa3\x52" "\x8f\x1c\xb4\x85\x60\xf7\x6b\x20\xf3\x82\xb9\x42\x50\x0f\xce\xac" } } }, { "ChaCha20 256 bit, TC3", GCRY_CIPHER_CHACHA20, 32, 8, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x01\x00\x00\x00\x00\x00\x00\x00", { { 128, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\xef\x3f\xdf\xd6\xc6\x15\x78\xfb\xf5\xcf\x35\xbd\x3d\xd3\x3b\x80" "\x09\x63\x16\x34\xd2\x1e\x42\xac\x33\x96\x0b\xd1\x38\xe5\x0d\x32" "\x11\x1e\x4c\xaf\x23\x7e\xe5\x3c\xa8\xad\x64\x26\x19\x4a\x88\x54" "\x5d\xdc\x49\x7a\x0b\x46\x6e\x7d\x6b\xbd\xb0\x04\x1b\x2f\x58\x6b" "\x53\x05\xe5\xe4\x4a\xff\x19\xb2\x35\x93\x61\x44\x67\x5e\xfb\xe4" "\x40\x9e\xb7\xe8\xe5\xf1\x43\x0f\x5f\x58\x36\xae\xb4\x9b\xb5\x32" "\x8b\x01\x7c\x4b\x9d\xc1\x1f\x8a\x03\x86\x3f\xa8\x03\xdc\x71\xd5" "\x72\x6b\x2b\x6b\x31\xaa\x32\x70\x8a\xfe\x5a\xf1\xd6\xb6\x90\x58" } } }, { "ChaCha20 256 bit, TC4", GCRY_CIPHER_CHACHA20, 32, 8, "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff", "\xff\xff\xff\xff\xff\xff\xff\xff", { { 128, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\xd9\xbf\x3f\x6b\xce\x6e\xd0\xb5\x42\x54\x55\x77\x67\xfb\x57\x44" "\x3d\xd4\x77\x89\x11\xb6\x06\x05\x5c\x39\xcc\x25\xe6\x74\xb8\x36" "\x3f\xea\xbc\x57\xfd\xe5\x4f\x79\x0c\x52\xc8\xae\x43\x24\x0b\x79" "\xd4\x90\x42\xb7\x77\xbf\xd6\xcb\x80\xe9\x31\x27\x0b\x7f\x50\xeb" "\x5b\xac\x2a\xcd\x86\xa8\x36\xc5\xdc\x98\xc1\x16\xc1\x21\x7e\xc3" "\x1d\x3a\x63\xa9\x45\x13\x19\xf0\x97\xf3\xb4\xd6\xda\xb0\x77\x87" "\x19\x47\x7d\x24\xd2\x4b\x40\x3a\x12\x24\x1d\x7c\xca\x06\x4f\x79" "\x0f\x1d\x51\xcc\xaf\xf6\xb1\x66\x7d\x4b\xbc\xa1\x95\x8c\x43\x06" } } }, { "ChaCha20 256 bit, TC5", GCRY_CIPHER_CHACHA20, 32, 8, "\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55" "\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55", "\x55\x55\x55\x55\x55\x55\x55\x55", { { 128, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\xbe\xa9\x41\x1a\xa4\x53\xc5\x43\x4a\x5a\xe8\xc9\x28\x62\xf5\x64" "\x39\x68\x55\xa9\xea\x6e\x22\xd6\xd3\xb5\x0a\xe1\xb3\x66\x33\x11" "\xa4\xa3\x60\x6c\x67\x1d\x60\x5c\xe1\x6c\x3a\xec\xe8\xe6\x1e\xa1" "\x45\xc5\x97\x75\x01\x7b\xee\x2f\xa6\xf8\x8a\xfc\x75\x80\x69\xf7" "\xe0\xb8\xf6\x76\xe6\x44\x21\x6f\x4d\x2a\x34\x22\xd7\xfa\x36\xc6" "\xc4\x93\x1a\xca\x95\x0e\x9d\xa4\x27\x88\xe6\xd0\xb6\xd1\xcd\x83" "\x8e\xf6\x52\xe9\x7b\x14\x5b\x14\x87\x1e\xae\x6c\x68\x04\xc7\x00" "\x4d\xb5\xac\x2f\xce\x4c\x68\xc7\x26\xd0\x04\xb1\x0f\xca\xba\x86" } } }, { "ChaCha20 256 bit, TC6", GCRY_CIPHER_CHACHA20, 32, 8, "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa", "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa", { { 128, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x9a\xa2\xa9\xf6\x56\xef\xde\x5a\xa7\x59\x1c\x5f\xed\x4b\x35\xae" "\xa2\x89\x5d\xec\x7c\xb4\x54\x3b\x9e\x9f\x21\xf5\xe7\xbc\xbc\xf3" "\xc4\x3c\x74\x8a\x97\x08\x88\xf8\x24\x83\x93\xa0\x9d\x43\xe0\xb7" "\xe1\x64\xbc\x4d\x0b\x0f\xb2\x40\xa2\xd7\x21\x15\xc4\x80\x89\x06" "\x72\x18\x44\x89\x44\x05\x45\xd0\x21\xd9\x7e\xf6\xb6\x93\xdf\xe5" "\xb2\xc1\x32\xd4\x7e\x6f\x04\x1c\x90\x63\x65\x1f\x96\xb6\x23\xe6" "\x2a\x11\x99\x9a\x23\xb6\xf7\xc4\x61\xb2\x15\x30\x26\xad\x5e\x86" "\x6a\x2e\x59\x7e\xd0\x7b\x84\x01\xde\xc6\x3a\x09\x34\xc6\xb2\xa9" } } }, { "ChaCha20 256 bit, TC7", GCRY_CIPHER_CHACHA20, 32, 8, "\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa\xbb\xcc\xdd\xee\xff" "\xff\xee\xdd\xcc\xbb\xaa\x99\x88\x77\x66\x55\x44\x33\x22\x11\x00", "\x0f\x1e\x2d\x3c\x4b\x5a\x69\x78", { { 128, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x9f\xad\xf4\x09\xc0\x08\x11\xd0\x04\x31\xd6\x7e\xfb\xd8\x8f\xba" "\x59\x21\x8d\x5d\x67\x08\xb1\xd6\x85\x86\x3f\xab\xbb\x0e\x96\x1e" "\xea\x48\x0f\xd6\xfb\x53\x2b\xfd\x49\x4b\x21\x51\x01\x50\x57\x42" "\x3a\xb6\x0a\x63\xfe\x4f\x55\xf7\xa2\x12\xe2\x16\x7c\xca\xb9\x31" "\xfb\xfd\x29\xcf\x7b\xc1\xd2\x79\xed\xdf\x25\xdd\x31\x6b\xb8\x84" "\x3d\x6e\xde\xe0\xbd\x1e\xf1\x21\xd1\x2f\xa1\x7c\xbc\x2c\x57\x4c" "\xcc\xab\x5e\x27\x51\x67\xb0\x8b\xd6\x86\xf8\xa0\x9d\xf8\x7e\xc3" "\xff\xb3\x53\x61\xb9\x4e\xbf\xa1\x3f\xec\x0e\x48\x89\xd1\x8d\xa5" } } }, { "ChaCha20 256 bit, TC8", GCRY_CIPHER_CHACHA20, 32, 8, "\xc4\x6e\xc1\xb1\x8c\xe8\xa8\x78\x72\x5a\x37\xe7\x80\xdf\xb7\x35" "\x1f\x68\xed\x2e\x19\x4c\x79\xfb\xc6\xae\xbe\xe1\xa6\x67\x97\x5d", "\x1a\xda\x31\xd5\xcf\x68\x82\x21", { { 128, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\xf6\x3a\x89\xb7\x5c\x22\x71\xf9\x36\x88\x16\x54\x2b\xa5\x2f\x06" "\xed\x49\x24\x17\x92\x30\x2b\x00\xb5\xe8\xf8\x0a\xe9\xa4\x73\xaf" "\xc2\x5b\x21\x8f\x51\x9a\xf0\xfd\xd4\x06\x36\x2e\x8d\x69\xde\x7f" "\x54\xc6\x04\xa6\xe0\x0f\x35\x3f\x11\x0f\x77\x1b\xdc\xa8\xab\x92" "\xe5\xfb\xc3\x4e\x60\xa1\xd9\xa9\xdb\x17\x34\x5b\x0a\x40\x27\x36" "\x85\x3b\xf9\x10\xb0\x60\xbd\xf1\xf8\x97\xb6\x29\x0f\x01\xd1\x38" "\xae\x2c\x4c\x90\x22\x5b\xa9\xea\x14\xd5\x18\xf5\x59\x29\xde\xa0" "\x98\xca\x7a\x6c\xcf\xe6\x12\x27\x05\x3c\x84\xe4\x9a\x4a\x33\x32" }, { 127, "\xf6\x3a\x89\xb7\x5c\x22\x71\xf9\x36\x88\x16\x54\x2b\xa5\x2f\x06" "\xed\x49\x24\x17\x92\x30\x2b\x00\xb5\xe8\xf8\x0a\xe9\xa4\x73\xaf" "\xc2\x5b\x21\x8f\x51\x9a\xf0\xfd\xd4\x06\x36\x2e\x8d\x69\xde\x7f" "\x54\xc6\x04\xa6\xe0\x0f\x35\x3f\x11\x0f\x77\x1b\xdc\xa8\xab\x92" "\xe5\xfb\xc3\x4e\x60\xa1\xd9\xa9\xdb\x17\x34\x5b\x0a\x40\x27\x36" "\x85\x3b\xf9\x10\xb0\x60\xbd\xf1\xf8\x97\xb6\x29\x0f\x01\xd1\x38" "\xae\x2c\x4c\x90\x22\x5b\xa9\xea\x14\xd5\x18\xf5\x59\x29\xde\xa0" "\x98\xca\x7a\x6c\xcf\xe6\x12\x27\x05\x3c\x84\xe4\x9a\x4a\x33", "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" } } }, /* from draft-nir-cfrg-chacha20-poly1305-02 */ { "ChaCha20 256 bit, IV96-bit", GCRY_CIPHER_CHACHA20, 32, 12, "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f" "\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f", "\x07\x00\x00\x00\x40\x41\x42\x43\x44\x45\x46\x47", { { 64, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x7b\xac\x2b\x25\x2d\xb4\x47\xaf\x09\xb6\x7a\x55\xa4\xe9\x55\x84" "\x0a\xe1\xd6\x73\x10\x75\xd9\xeb\x2a\x93\x75\x78\x3e\xd5\x53\xff" "\xa2\x7e\xcc\xde\xad\xdb\x4d\xb4\xd1\x17\x9c\xe4\xc9\x0b\x43\xd8" "\xbc\xb7\x94\x8c\x4b\x4b\x7d\x8b\x7d\xf6\x27\x39\x32\xa4\x69\x16" }, }, }, #endif /*USE_CHACHA20*/ }; gcry_cipher_hd_t hde, hdd; unsigned char out[MAX_DATA_LEN]; int i, j; gcry_error_t err = 0; if (verbose) fprintf (stderr, " Starting stream cipher checks.\n"); for (i = 0; i < sizeof (tv) / sizeof (tv[0]); i++) { if (gcry_cipher_test_algo (tv[i].algo) && in_fips_mode) { if (verbose) fprintf (stderr, " algorithm %d not available in fips mode\n", tv[i].algo); continue; } if (verbose) fprintf (stderr, " checking stream mode for %s [%i] (%s)\n", gcry_cipher_algo_name (tv[i].algo), tv[i].algo, tv[i].name); if (gcry_cipher_get_algo_blklen(tv[i].algo) != 1) { fail ("stream, gcry_cipher_get_algo_blklen: bad block length\n"); continue; } err = gcry_cipher_open (&hde, tv[i].algo, GCRY_CIPHER_MODE_STREAM, 0); if (!err) err = gcry_cipher_open (&hdd, tv[i].algo, GCRY_CIPHER_MODE_STREAM, 0); if (err) { fail ("stream, gcry_cipher_open for stream mode failed: %s\n", gpg_strerror (err)); continue; } /* Now loop over all the data samples. */ for (j = 0; tv[i].data[j].inlen; j++) { err = gcry_cipher_setkey (hde, tv[i].key, tv[i].keylen); if (!err) err = gcry_cipher_setkey (hdd, tv[i].key, tv[i].keylen); if (err) { fail ("stream, gcry_cipher_setkey failed: %s\n", gpg_strerror (err)); goto next; } err = gcry_cipher_setiv (hde, tv[i].iv, tv[i].ivlen); if (!err) err = gcry_cipher_setiv (hdd, tv[i].iv, tv[i].ivlen); if (err) { fail ("stream, gcry_cipher_setiv failed: %s\n", gpg_strerror (err)); goto next; } err = gcry_cipher_encrypt (hde, out, MAX_DATA_LEN, tv[i].data[j].plaintext, tv[i].data[j].inlen); if (err) { fail ("stream, gcry_cipher_encrypt (%d, %d) failed: %s\n", i, j, gpg_strerror (err)); goto next; } if (memcmp (tv[i].data[j].out, out, tv[i].data[j].inlen)) { fail ("stream, encrypt mismatch entry %d:%d\n", i, j); mismatch (tv[i].data[j].out, tv[i].data[j].inlen, out, tv[i].data[j].inlen); } err = gcry_cipher_decrypt (hdd, out, tv[i].data[j].inlen, NULL, 0); if (err) { fail ("stream, gcry_cipher_decrypt (%d, %d) failed: %s\n", i, j, gpg_strerror (err)); goto next; } if (memcmp (tv[i].data[j].plaintext, out, tv[i].data[j].inlen)) fail ("stream, decrypt mismatch entry %d:%d\n", i, j); } /* This time we encrypt and decrypt one byte at a time */ for (j = 0; tv[i].data[j].inlen; j++) { int byteNum; err = gcry_cipher_setkey (hde, tv[i].key, tv[i].keylen); if (!err) err = gcry_cipher_setkey (hdd, tv[i].key, tv[i].keylen); if (err) { fail ("stream, gcry_cipher_setkey failed: %s\n", gpg_strerror (err)); goto next; } err = gcry_cipher_setiv (hde, tv[i].iv, tv[i].ivlen); if (!err) err = gcry_cipher_setiv (hdd, tv[i].iv, tv[i].ivlen); if (err) { fail ("stream, gcry_cipher_setiv failed: %s\n", gpg_strerror (err)); goto next; } for (byteNum = 0; byteNum < tv[i].data[j].inlen; ++byteNum) { err = gcry_cipher_encrypt (hde, out+byteNum, 1, (tv[i].data[j].plaintext) + byteNum, 1); if (err) { fail ("stream, gcry_cipher_encrypt (%d, %d) failed: %s\n", i, j, gpg_strerror (err)); goto next; } } if (memcmp (tv[i].data[j].out, out, tv[i].data[j].inlen)) fail ("stream, encrypt mismatch entry %d:%d (byte-wise)\n", i, j); for (byteNum = 0; byteNum < tv[i].data[j].inlen; ++byteNum) { err = gcry_cipher_decrypt (hdd, out+byteNum, 1, NULL, 0); if (err) { fail ("stream, gcry_cipher_decrypt (%d, %d) failed: %s\n", i, j, gpg_strerror (err)); goto next; } } if (memcmp (tv[i].data[j].plaintext, out, tv[i].data[j].inlen)) fail ("stream, decrypt mismatch entry %d:%d (byte-wise)\n", i, j); } next: gcry_cipher_close (hde); gcry_cipher_close (hdd); } if (verbose) fprintf (stderr, " Completed stream cipher checks.\n"); } static void check_stream_cipher_large_block (void) { static const struct tv { const char *name; int algo; int keylen; int ivlen; const char *key; const char *iv; struct data { int offset, length; const char *result; } data[MAX_DATA_LEN]; } tv[] = { #ifdef USE_SALSA20 { "Salsa20 256 bit, ecrypt verified, set 6, vector 0", GCRY_CIPHER_SALSA20, 32, 8, "\x00\x53\xA6\xF9\x4C\x9F\xF2\x45\x98\xEB\x3E\x91\xE4\x37\x8A\xDD" "\x30\x83\xD6\x29\x7C\xCF\x22\x75\xC8\x1B\x6E\xC1\x14\x67\xBA\x0D", "\x0D\x74\xDB\x42\xA9\x10\x77\xDE", { { 0, 64, "\xF5\xFA\xD5\x3F\x79\xF9\xDF\x58\xC4\xAE\xA0\xD0\xED\x9A\x96\x01" "\xF2\x78\x11\x2C\xA7\x18\x0D\x56\x5B\x42\x0A\x48\x01\x96\x70\xEA" "\xF2\x4C\xE4\x93\xA8\x62\x63\xF6\x77\xB4\x6A\xCE\x19\x24\x77\x3D" "\x2B\xB2\x55\x71\xE1\xAA\x85\x93\x75\x8F\xC3\x82\xB1\x28\x0B\x71" }, { 65472, 64, "\xB7\x0C\x50\x13\x9C\x63\x33\x2E\xF6\xE7\x7A\xC5\x43\x38\xA4\x07" "\x9B\x82\xBE\xC9\xF9\xA4\x03\xDF\xEA\x82\x1B\x83\xF7\x86\x07\x91" "\x65\x0E\xF1\xB2\x48\x9D\x05\x90\xB1\xDE\x77\x2E\xED\xA4\xE3\xBC" "\xD6\x0F\xA7\xCE\x9C\xD6\x23\xD9\xD2\xFD\x57\x58\xB8\x65\x3E\x70" }, { 65536, 64, "\x81\x58\x2C\x65\xD7\x56\x2B\x80\xAE\xC2\xF1\xA6\x73\xA9\xD0\x1C" "\x9F\x89\x2A\x23\xD4\x91\x9F\x6A\xB4\x7B\x91\x54\xE0\x8E\x69\x9B" "\x41\x17\xD7\xC6\x66\x47\x7B\x60\xF8\x39\x14\x81\x68\x2F\x5D\x95" "\xD9\x66\x23\xDB\xC4\x89\xD8\x8D\xAA\x69\x56\xB9\xF0\x64\x6B\x6E" }, { 131008, 64, "\xA1\x3F\xFA\x12\x08\xF8\xBF\x50\x90\x08\x86\xFA\xAB\x40\xFD\x10" "\xE8\xCA\xA3\x06\xE6\x3D\xF3\x95\x36\xA1\x56\x4F\xB7\x60\xB2\x42" "\xA9\xD6\xA4\x62\x8C\xDC\x87\x87\x62\x83\x4E\x27\xA5\x41\xDA\x2A" "\x5E\x3B\x34\x45\x98\x9C\x76\xF6\x11\xE0\xFE\xC6\xD9\x1A\xCA\xCC" } } }, { "Salsa20 256 bit, ecrypt verified, set 6, vector 1", GCRY_CIPHER_SALSA20, 32, 8, "\x05\x58\xAB\xFE\x51\xA4\xF7\x4A\x9D\xF0\x43\x96\xE9\x3C\x8F\xE2" "\x35\x88\xDB\x2E\x81\xD4\x27\x7A\xCD\x20\x73\xC6\x19\x6C\xBF\x12", "\x16\x7D\xE4\x4B\xB2\x19\x80\xE7", { { 0, 64, "\x39\x44\xF6\xDC\x9F\x85\xB1\x28\x08\x38\x79\xFD\xF1\x90\xF7\xDE" "\xE4\x05\x3A\x07\xBC\x09\x89\x6D\x51\xD0\x69\x0B\xD4\xDA\x4A\xC1" "\x06\x2F\x1E\x47\xD3\xD0\x71\x6F\x80\xA9\xB4\xD8\x5E\x6D\x60\x85" "\xEE\x06\x94\x76\x01\xC8\x5F\x1A\x27\xA2\xF7\x6E\x45\xA6\xAA\x87" }, { 65472, 64, "\x36\xE0\x3B\x4B\x54\xB0\xB2\xE0\x4D\x06\x9E\x69\x00\x82\xC8\xC5" "\x92\xDF\x56\xE6\x33\xF5\xD8\xC7\x68\x2A\x02\xA6\x5E\xCD\x13\x71" "\x8C\xA4\x35\x2A\xAC\xCB\x0D\xA2\x0E\xD6\xBB\xBA\x62\xE1\x77\xF2" "\x10\xE3\x56\x0E\x63\xBB\x82\x2C\x41\x58\xCA\xA8\x06\xA8\x8C\x82" }, { 65536, 64, "\x1B\x77\x9E\x7A\x91\x7C\x8C\x26\x03\x9F\xFB\x23\xCF\x0E\xF8\xE0" "\x8A\x1A\x13\xB4\x3A\xCD\xD9\x40\x2C\xF5\xDF\x38\x50\x10\x98\xDF" "\xC9\x45\xA6\xCC\x69\xA6\xA1\x73\x67\xBC\x03\x43\x1A\x86\xB3\xED" "\x04\xB0\x24\x5B\x56\x37\x9B\xF9\x97\xE2\x58\x00\xAD\x83\x7D\x7D" }, { 131008, 64, "\x7E\xC6\xDA\xE8\x1A\x10\x5E\x67\x17\x2A\x0B\x8C\x4B\xBE\x7D\x06" "\xA7\xA8\x75\x9F\x91\x4F\xBE\xB1\xAF\x62\xC8\xA5\x52\xEF\x4A\x4F" "\x56\x96\x7E\xA2\x9C\x74\x71\xF4\x6F\x3B\x07\xF7\xA3\x74\x6E\x95" "\x3D\x31\x58\x21\xB8\x5B\x6E\x8C\xB4\x01\x22\xB9\x66\x35\x31\x3C" } } }, { "Salsa20 256 bit, ecrypt verified, set 6, vector 2", GCRY_CIPHER_SALSA20, 32, 8, "\x0A\x5D\xB0\x03\x56\xA9\xFC\x4F\xA2\xF5\x48\x9B\xEE\x41\x94\xE7" "\x3A\x8D\xE0\x33\x86\xD9\x2C\x7F\xD2\x25\x78\xCB\x1E\x71\xC4\x17", "\x1F\x86\xED\x54\xBB\x22\x89\xF0", { { 0, 64, "\x3F\xE8\x5D\x5B\xB1\x96\x0A\x82\x48\x0B\x5E\x6F\x4E\x96\x5A\x44" "\x60\xD7\xA5\x45\x01\x66\x4F\x7D\x60\xB5\x4B\x06\x10\x0A\x37\xFF" "\xDC\xF6\xBD\xE5\xCE\x3F\x48\x86\xBA\x77\xDD\x5B\x44\xE9\x56\x44" "\xE4\x0A\x8A\xC6\x58\x01\x15\x5D\xB9\x0F\x02\x52\x2B\x64\x40\x23" }, { 65472, 64, "\xC8\xD6\xE5\x4C\x29\xCA\x20\x40\x18\xA8\x30\xE2\x66\xCE\xEE\x0D" "\x03\x7D\xC4\x7E\x92\x19\x47\x30\x2A\xCE\x40\xD1\xB9\x96\xA6\xD8" "\x0B\x59\x86\x77\xF3\x35\x2F\x1D\xAA\x6D\x98\x88\xF8\x91\xAD\x95" "\xA1\xC3\x2F\xFE\xB7\x1B\xB8\x61\xE8\xB0\x70\x58\x51\x51\x71\xC9" }, { 65536, 64, "\xB7\x9F\xD7\x76\x54\x2B\x46\x20\xEF\xCB\x88\x44\x95\x99\xF2\x34" "\x03\xE7\x4A\x6E\x91\xCA\xCC\x50\xA0\x5A\x8F\x8F\x3C\x0D\xEA\x8B" "\x00\xE1\xA5\xE6\x08\x1F\x55\x26\xAE\x97\x5B\x3B\xC0\x45\x0F\x1A" "\x0C\x8B\x66\xF8\x08\xF1\x90\x4B\x97\x13\x61\x13\x7C\x93\x15\x6F" }, { 131008, 64, "\x79\x98\x20\x4F\xED\x70\xCE\x8E\x0D\x02\x7B\x20\x66\x35\xC0\x8C" "\x8B\xC4\x43\x62\x26\x08\x97\x0E\x40\xE3\xAE\xDF\x3C\xE7\x90\xAE" "\xED\xF8\x9F\x92\x26\x71\xB4\x53\x78\xE2\xCD\x03\xF6\xF6\x23\x56" "\x52\x9C\x41\x58\xB7\xFF\x41\xEE\x85\x4B\x12\x35\x37\x39\x88\xC8" } } }, { "Salsa20 256 bit, ecrypt verified, set 6, vector 3", GCRY_CIPHER_SALSA20, 32, 8, "\x0F\x62\xB5\x08\x5B\xAE\x01\x54\xA7\xFA\x4D\xA0\xF3\x46\x99\xEC" "\x3F\x92\xE5\x38\x8B\xDE\x31\x84\xD7\x2A\x7D\xD0\x23\x76\xC9\x1C", "\x28\x8F\xF6\x5D\xC4\x2B\x92\xF9", { { 0, 64, "\x5E\x5E\x71\xF9\x01\x99\x34\x03\x04\xAB\xB2\x2A\x37\xB6\x62\x5B" "\xF8\x83\xFB\x89\xCE\x3B\x21\xF5\x4A\x10\xB8\x10\x66\xEF\x87\xDA" "\x30\xB7\x76\x99\xAA\x73\x79\xDA\x59\x5C\x77\xDD\x59\x54\x2D\xA2" "\x08\xE5\x95\x4F\x89\xE4\x0E\xB7\xAA\x80\xA8\x4A\x61\x76\x66\x3F" }, { 65472, 64, "\x2D\xA2\x17\x4B\xD1\x50\xA1\xDF\xEC\x17\x96\xE9\x21\xE9\xD6\xE2" "\x4E\xCF\x02\x09\xBC\xBE\xA4\xF9\x83\x70\xFC\xE6\x29\x05\x6F\x64" "\x91\x72\x83\x43\x6E\x2D\x3F\x45\x55\x62\x25\x30\x7D\x5C\xC5\xA5" "\x65\x32\x5D\x89\x93\xB3\x7F\x16\x54\x19\x5C\x24\x0B\xF7\x5B\x16" }, { 65536, 64, "\xAB\xF3\x9A\x21\x0E\xEE\x89\x59\x8B\x71\x33\x37\x70\x56\xC2\xFE" "\xF4\x2D\xA7\x31\x32\x75\x63\xFB\x67\xC7\xBE\xDB\x27\xF3\x8C\x7C" "\x5A\x3F\xC2\x18\x3A\x4C\x6B\x27\x7F\x90\x11\x52\x47\x2C\x6B\x2A" "\xBC\xF5\xE3\x4C\xBE\x31\x5E\x81\xFD\x3D\x18\x0B\x5D\x66\xCB\x6C" }, { 131008, 64, "\x1B\xA8\x9D\xBD\x3F\x98\x83\x97\x28\xF5\x67\x91\xD5\xB7\xCE\x23" "\x50\x36\xDE\x84\x3C\xCC\xAB\x03\x90\xB8\xB5\x86\x2F\x1E\x45\x96" "\xAE\x8A\x16\xFB\x23\xDA\x99\x7F\x37\x1F\x4E\x0A\xAC\xC2\x6D\xB8" "\xEB\x31\x4E\xD4\x70\xB1\xAF\x6B\x9F\x8D\x69\xDD\x79\xA9\xD7\x50" } } }, { "Salsa20/12 256 bit, ecrypt verified, set 6, vector 0", GCRY_CIPHER_SALSA20R12, 32, 8, "\x00\x53\xA6\xF9\x4C\x9F\xF2\x45\x98\xEB\x3E\x91\xE4\x37\x8A\xDD" "\x30\x83\xD6\x29\x7C\xCF\x22\x75\xC8\x1B\x6E\xC1\x14\x67\xBA\x0D", "\x0D\x74\xDB\x42\xA9\x10\x77\xDE", { { 0, 64, "\x52\xE2\x0C\xF8\x77\x5A\xE8\x82\xF2\x00\xC2\x99\x9F\xE4\xBA\x31" "\xA7\xA1\x8F\x1D\x5C\x97\x16\x19\x1D\x12\x31\x75\xE1\x47\xBD\x4E" "\x8C\xA6\xED\x16\x6C\xE0\xFC\x8E\x65\xA5\xCA\x60\x84\x20\xFC\x65" "\x44\xC9\x70\x0A\x0F\x21\x38\xE8\xC1\xA2\x86\xFB\x8C\x1F\xBF\xA0" }, { 65472, 64, "\x8F\xBC\x9F\xE8\x69\x1B\xD4\xF0\x82\xB4\x7F\x54\x05\xED\xFB\xC1" "\x6F\x4D\x5A\x12\xDD\xCB\x2D\x75\x4E\x8A\x99\x98\xD0\xB2\x19\x55" "\x7D\xFE\x29\x84\xF4\xA1\xD2\xDD\xA7\x6B\x95\x96\x92\x8C\xCE\x05" "\x56\xF5\x00\x66\xCD\x59\x9E\x44\xEF\x5C\x14\xB2\x26\x68\x3A\xEF" }, { 65536, 64, "\xBC\xBD\x01\xDD\x28\x96\x1C\xC7\xAD\x30\x47\x38\x6C\xBC\xC6\x7C" "\x10\x8D\x6A\xF1\x11\x67\xE4\x0D\x7A\xE1\xB2\xFC\x45\x18\xA8\x67" "\xEF\xE4\x02\x65\x1D\x1D\x88\x51\xC4\xFD\x23\x30\xC5\x97\xB3\x6A" "\x46\xD5\x68\x9E\x00\xFC\x96\xFE\xCF\x9C\xE3\xE2\x21\x1D\x44\xBE" }, { 131008, 64, "\x91\x66\xF3\x1C\xD8\x5B\x5B\xB1\x8F\xC6\x14\xE5\x4E\x4A\xD6\x7F" "\xB8\x65\x8E\x3B\xF9\xFB\x19\xB7\xA8\x2F\x0F\xE7\xDC\x90\x2D\xF5" "\x63\xC6\xAC\x4F\x44\x67\x48\xC4\xBC\x3E\x14\x05\xE1\x24\x82\x0D" "\xC4\x09\x41\x99\x8F\x44\xA8\x10\xE7\x22\x78\x7F\xCD\x47\x78\x4C" } } }, { "Salsa20/12 256 bit, ecrypt verified, set 6, vector 1", GCRY_CIPHER_SALSA20R12, 32, 8, "\x05\x58\xAB\xFE\x51\xA4\xF7\x4A\x9D\xF0\x43\x96\xE9\x3C\x8F\xE2" "\x35\x88\xDB\x2E\x81\xD4\x27\x7A\xCD\x20\x73\xC6\x19\x6C\xBF\x12", "\x16\x7D\xE4\x4B\xB2\x19\x80\xE7", { { 0, 64, "\xC0\x75\x60\xB3\xE7\x76\xB4\x71\xC5\xE2\x93\x14\x26\xCA\xF1\xED" "\x3A\xE4\xB8\x67\x08\x76\x82\xCA\x9D\xFD\xC2\xBA\xE8\x93\x50\xBD" "\x84\x82\x1C\xAE\xFF\x85\xAA\xC4\x9D\x74\x35\xA7\xD9\x88\x93\x52" "\xF5\x27\x9E\x36\x12\x3F\x41\x72\x8A\x14\xEF\x26\x9F\xCB\x94\x4B" }, { 65472, 64, "\xEE\xD1\xBB\x58\xF9\x0C\x89\xE0\x5C\xC6\x8B\x2D\xB6\x05\x58\x49" "\xB3\xD2\xB1\x87\xB7\xF0\x2F\x9A\x24\xCE\x34\x2A\xF0\xFC\x47\xA3" "\x74\xBD\x75\x90\xFB\xF4\xFD\x9E\xE5\x9B\x1A\x38\x1E\xBF\xD2\x29" "\xAD\x2A\x29\x01\xB3\xFB\x61\x08\x12\x90\x0B\x92\x30\xE6\x22\xE9" }, { 65536, 64, "\x70\xF0\x49\x3A\x1B\x62\x53\xCC\x5E\xD3\x45\x0A\x31\xCF\x37\x7D" "\x83\x4B\xAD\x20\x72\x30\x29\x27\xCC\xD8\x30\x10\x4B\xD3\x05\xFF" "\x59\xD2\x94\x17\xB2\x32\x88\x4E\xC9\x59\x19\x4D\x60\x47\xC3\xDD" "\x66\x56\xC4\x7E\x32\x00\x64\xEB\x01\x44\xF7\x34\x1B\xC3\xD6\x97" }, { 131008, 64, "\xD2\xCC\xF7\xC1\xAF\x2A\xB4\x66\xE6\x27\xDB\x44\x08\x40\x96\x9A" "\xBD\xAB\x68\xD8\x86\xAE\x6A\x38\xA1\x3F\xEE\x17\x50\xCA\x97\xB5" "\xD3\x31\x5B\x84\x08\x47\x28\x86\x2F\xBC\xC7\xD4\xA9\x7C\x75\xC8" "\x65\x5F\xF9\xD6\xBB\xC2\x61\x88\x63\x6F\x3E\xDF\xE1\x5C\x7D\x30" } } }, { "Salsa20/12 256 bit, ecrypt verified, set 6, vector 2", GCRY_CIPHER_SALSA20R12, 32, 8, "\x0A\x5D\xB0\x03\x56\xA9\xFC\x4F\xA2\xF5\x48\x9B\xEE\x41\x94\xE7" "\x3A\x8D\xE0\x33\x86\xD9\x2C\x7F\xD2\x25\x78\xCB\x1E\x71\xC4\x17", "\x1F\x86\xED\x54\xBB\x22\x89\xF0", { { 0, 64, "\x51\x22\x52\x91\x01\x90\xD1\x54\xD1\x4D\x0B\x92\x32\xB8\x84\x31" "\x8C\xCB\x43\x81\x9B\xD5\x42\x19\x32\xC0\x3A\x13\xF0\x7B\x40\x10" "\x83\xD7\x89\x72\x5A\xA9\xDA\x0B\x41\xCB\x62\x24\x94\x5E\xDC\xB0" "\xFB\x6F\xD7\xC2\x34\x22\x35\xC9\x70\xF6\x4E\x10\x1C\x25\x68\x64" }, { 65472, 64, "\x97\x96\x74\x55\x84\x0A\x4A\xE5\xC1\xCA\xCE\x49\x15\x19\x13\x8A" "\xA3\x5E\x5F\x02\x40\x7D\x4A\x1F\xE5\x08\x6D\x35\xF3\x55\x1E\xF4" "\x77\xD9\x28\x9D\x17\x23\x79\x7C\x1A\x49\xEC\x26\x62\x9A\xFA\xDC" "\x56\xA0\x38\xA3\x8C\x75\x88\x1B\x62\x17\xFD\x74\x67\x25\x59\x09" }, { 65536, 64, "\x1B\xF8\x2E\x3D\x5C\x54\xDA\xAB\xCF\x84\x15\xF8\xA2\xA1\xA2\x2E" "\x86\x88\x06\x33\x4F\xF3\x11\x36\x04\x74\x1C\x1D\xF2\xB9\x84\x0F" "\x87\xDE\xEF\xB0\x07\x23\xA8\xA1\xB2\x4A\x4D\xA1\x7E\xCD\xAD\x00" "\x01\xF9\x79\xDD\xAE\x2D\xF0\xC5\xE1\xE5\x32\xC4\x8F\x8E\x0D\x34" }, { 131008, 64, "\x06\xD8\x4F\x6A\x71\x34\x84\x20\x32\x9F\xCD\x0C\x41\x75\x9A\xD1" "\x8F\x99\x57\xA3\x8F\x22\x89\x3B\xA5\x58\xC5\x05\x11\x97\x28\x5C" "\x6B\xE2\xFD\x6C\x96\xA5\xC6\x62\xAF\xD3\x11\x78\xE7\x0F\x96\x0A" "\xAB\x3F\x47\x96\x23\xA4\x44\xB6\x81\x91\xE4\xC5\x28\x46\x93\x88" } } }, { "Salsa20/12 256 bit, ecrypt verified, set 6, vector 3", GCRY_CIPHER_SALSA20R12, 32, 8, "\x0F\x62\xB5\x08\x5B\xAE\x01\x54\xA7\xFA\x4D\xA0\xF3\x46\x99\xEC" "\x3F\x92\xE5\x38\x8B\xDE\x31\x84\xD7\x2A\x7D\xD0\x23\x76\xC9\x1C", "\x28\x8F\xF6\x5D\xC4\x2B\x92\xF9", { { 0, 64, "\x99\xDB\x33\xAD\x11\xCE\x0C\xCB\x3B\xFD\xBF\x8D\x0C\x18\x16\x04" "\x52\xD0\x14\xCD\xE9\x89\xB4\xC4\x11\xA5\x59\xFF\x7C\x20\xA1\x69" "\xE6\xDC\x99\x09\xD8\x16\xBE\xCE\xDC\x40\x63\xCE\x07\xCE\xA8\x28" "\xF4\x4B\xF9\xB6\xC9\xA0\xA0\xB2\x00\xE1\xB5\x2A\xF4\x18\x59\xC5" }, { 65472, 64, "\x2F\xF2\x02\x64\xEE\xAF\x47\xAB\x7D\x57\xC3\x62\x24\x53\x54\x51" "\x73\x5A\xC8\x36\xD3\x2D\xD2\x8A\xE6\x36\x45\xCE\x95\x2F\x7F\xDB" "\xE6\x68\x9C\x69\x59\x77\xB1\xC7\x6E\x60\xDD\x5B\x27\xAC\xA4\x76" "\xD2\x62\x0F\xDC\x93\x13\xE8\x48\x9B\xA5\x6A\x70\xC9\xF4\xC3\xA8" }, { 65536, 64, "\xEB\x30\xCD\xA7\x27\xC0\xF8\xB7\xE4\x5D\x5E\xF3\x0D\xB7\xCB\xE0" "\x21\xF2\x29\x1E\x5F\x56\x93\x8D\x56\xF6\x87\xB7\x37\xC3\xB4\x27" "\x54\x5C\x56\xA6\xD3\xA0\xBF\x2B\x2F\x47\xB4\x84\x93\xFA\xE4\x5E" "\xD5\x0C\x2E\x9B\xBE\x49\xFD\x92\xD6\x7C\x76\x49\x05\x5F\x06\xFD" }, { 131008, 64, "\x0E\xBF\x6C\xC3\xCB\xCB\xE7\x4E\x6E\xE8\x07\x47\x1B\x49\x2A\x67" "\x39\xA5\x2F\x57\x11\x31\xA2\x50\xBC\xDF\xA0\x76\xA2\x65\x90\xD7" "\xED\xE6\x75\x1C\x03\x26\xA0\x2C\xB1\x1C\x58\x77\x35\x52\x80\x4F" "\xD8\x68\x67\x15\x35\x5C\x5A\x5C\xC5\x91\x96\x3A\x75\xE9\x94\xB4" } } } #endif /*USE_SALSA20*/ }; char zeroes[512]; gcry_cipher_hd_t hde; unsigned char *buffer; unsigned char *p; size_t buffersize; unsigned int n; int i, j; gcry_error_t err = 0; if (verbose) fprintf (stderr, " Starting large block stream cipher checks.\n"); memset (zeroes, 0, 512); buffersize = 128 * 1024; buffer = gcry_xmalloc (buffersize+1024); memset (buffer+buffersize, 0x5a, 1024); for (i = 0; i < sizeof (tv) / sizeof (tv[0]); i++) { if (gcry_cipher_test_algo (tv[i].algo) && in_fips_mode) { if (verbose) fprintf (stderr, " algorithm %d not available in fips mode\n", tv[i].algo); continue; } if (verbose) fprintf (stderr, " checking large block stream for %s [%i] (%s)\n", gcry_cipher_algo_name (tv[i].algo), tv[i].algo, tv[i].name); err = gcry_cipher_open (&hde, tv[i].algo, GCRY_CIPHER_MODE_STREAM, 0); if (err) { fail ("large stream, gcry_cipher_open for stream mode failed: %s\n", gpg_strerror (err)); continue; } err = gcry_cipher_setkey (hde, tv[i].key, tv[i].keylen); if (err) { fail ("large stream, gcry_cipher_setkey failed: %s\n", gpg_strerror (err)); goto next; } err = gcry_cipher_setiv (hde, tv[i].iv, tv[i].ivlen); if (err) { fail ("large stream, gcry_cipher_setiv failed: %s\n", gpg_strerror (err)); goto next; } for (j=0, p=buffer; j < buffersize/512; j++, p += 512) { err = gcry_cipher_encrypt (hde, p, 512, zeroes, 512); if (err) { fail ("large stream, " "gcry_cipher_encrypt (%d) block %d failed: %s\n", i, j, gpg_strerror (err)); goto next; } } for (j=0, p=buffer+buffersize; j < 1024; j++, p++) if (*p != 0x5a) die ("large stream, buffer corrupted at j=%d\n", j); /* Now loop over all the data samples. */ for (j = 0; tv[i].data[j].length; j++) { assert (tv[i].data[j].offset + tv[i].data[j].length <= buffersize); if (memcmp (tv[i].data[j].result, buffer + tv[i].data[j].offset, tv[i].data[j].length)) { fail ("large stream, encrypt mismatch entry %d:%d\n", i, j); mismatch (tv[i].data[j].result, tv[i].data[j].length, buffer + tv[i].data[j].offset, tv[i].data[j].length); } } /* * Let's do the same thing again but using changing block sizes. */ err = gcry_cipher_setkey (hde, tv[i].key, tv[i].keylen); if (err) { fail ("large stream, gcry_cipher_setkey failed: %s\n", gpg_strerror (err)); goto next; } err = gcry_cipher_setiv (hde, tv[i].iv, tv[i].ivlen); if (err) { fail ("large stream, gcry_cipher_setiv failed: %s\n", gpg_strerror (err)); goto next; } for (n=0, p=buffer, j = 0; n < buffersize; n += j, p += j) { switch (j) { case 0: j = 1; break; case 1: j = 64; break; case 64: j= 384; break; case 384: j = 63; break; case 63: j = 512; break; case 512: j = 32; break; case 32: j = 503; break; default: j = 509; break; } if ( n + j >= buffersize ) j = buffersize - n; assert (j <= 512); err = gcry_cipher_encrypt (hde, p, j, zeroes, j); if (err) { fail ("large stream, " "gcry_cipher_encrypt (%d) offset %u failed: %s\n", i, n, gpg_strerror (err)); goto next; } } for (j=0, p=buffer+buffersize; j < 1024; j++, p++) if (*p != 0x5a) die ("large stream, buffer corrupted at j=%d (line %d)\n", j, __LINE__); /* Now loop over all the data samples. */ for (j = 0; tv[i].data[j].length; j++) { assert (tv[i].data[j].offset + tv[i].data[j].length <= buffersize); if (memcmp (tv[i].data[j].result, buffer + tv[i].data[j].offset, tv[i].data[j].length)) { fail ("large stream var, encrypt mismatch entry %d:%d\n", i, j); mismatch (tv[i].data[j].result, tv[i].data[j].length, buffer + tv[i].data[j].offset, tv[i].data[j].length); } } next: gcry_cipher_close (hde); } gcry_free (buffer); if (verbose) fprintf (stderr, " Completed large block stream cipher checks.\n"); } -/* Check that our bulk encryption fucntions work properly. */ +/* Check that our bulk encryption functions work properly. */ static void check_bulk_cipher_modes (void) { static const struct { int algo; int mode; const char *key; int keylen; const char *iv; int ivlen; char t1_hash[20]; } tv[] = { { GCRY_CIPHER_AES, GCRY_CIPHER_MODE_CFB, "abcdefghijklmnop", 16, "1234567890123456", 16, /*[0]*/ { 0x53, 0xda, 0x27, 0x3c, 0x78, 0x3d, 0x54, 0x66, 0x19, 0x63, 0xd7, 0xe6, 0x20, 0x10, 0xcd, 0xc0, 0x5a, 0x0b, 0x06, 0xcc } }, { GCRY_CIPHER_AES192, GCRY_CIPHER_MODE_CFB, "abcdefghijklmnopABCDEFG", 24, "1234567890123456", 16, /*[1]*/ { 0xc7, 0xb1, 0xd0, 0x09, 0x95, 0x04, 0x34, 0x61, 0x2b, 0xd9, 0xcb, 0xb3, 0xc7, 0xcb, 0xef, 0xea, 0x16, 0x19, 0x9b, 0x3e } }, { GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CFB, "abcdefghijklmnopABCDEFGHIJKLMNOP", 32, "1234567890123456", 16, /*[2]*/ { 0x31, 0xe1, 0x1f, 0x63, 0x65, 0x47, 0x8c, 0x3f, 0x53, 0xdb, 0xd9, 0x4d, 0x91, 0x1d, 0x02, 0x9c, 0x05, 0x25, 0x58, 0x29 } }, { GCRY_CIPHER_AES, GCRY_CIPHER_MODE_CBC, "abcdefghijklmnop", 16, "1234567890123456", 16, /*[3]*/ { 0xdc, 0x0c, 0xc2, 0xd9, 0x6b, 0x47, 0xf9, 0xeb, 0x06, 0xb4, 0x2f, 0x6e, 0xec, 0x72, 0xbf, 0x55, 0x26, 0x7f, 0xa9, 0x97 } }, { GCRY_CIPHER_AES192, GCRY_CIPHER_MODE_CBC, "abcdefghijklmnopABCDEFG", 24, "1234567890123456", 16, /*[4]*/ { 0x2b, 0x90, 0x9b, 0xe6, 0x40, 0xab, 0x6e, 0xc2, 0xc5, 0xb1, 0x87, 0xf5, 0x43, 0x84, 0x7b, 0x04, 0x06, 0x47, 0xd1, 0x8f } }, { GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CBC, "abcdefghijklmnopABCDEFGHIJKLMNOP", 32, "1234567890123456", 16, /*[5]*/ { 0xaa, 0xa8, 0xdf, 0x03, 0xb0, 0xba, 0xc4, 0xe3, 0xc1, 0x02, 0x38, 0x31, 0x8d, 0x86, 0xcb, 0x49, 0x6d, 0xad, 0xae, 0x01 } }, { GCRY_CIPHER_AES, GCRY_CIPHER_MODE_OFB, "abcdefghijklmnop", 16, "1234567890123456", 16, /*[6]*/ { 0x65, 0xfe, 0xde, 0x48, 0xd0, 0xa1, 0xa6, 0xf9, 0x24, 0x6b, 0x52, 0x5f, 0x21, 0x8a, 0x6f, 0xc7, 0x70, 0x3b, 0xd8, 0x4a } }, { GCRY_CIPHER_AES192, GCRY_CIPHER_MODE_OFB, "abcdefghijklmnopABCDEFG", 24, "1234567890123456", 16, /*[7]*/ { 0x59, 0x5b, 0x02, 0xa2, 0x88, 0xc0, 0xbe, 0x94, 0x43, 0xaa, 0x39, 0xf6, 0xbd, 0xcc, 0x83, 0x99, 0xee, 0x00, 0xa1, 0x91 } }, { GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_OFB, "abcdefghijklmnopABCDEFGHIJKLMNOP", 32, "1234567890123456", 16, /*[8]*/ { 0x38, 0x8c, 0xe1, 0xe2, 0xbe, 0x67, 0x60, 0xe8, 0xeb, 0xce, 0xd0, 0xc6, 0xaa, 0xd6, 0xf6, 0x26, 0x15, 0x56, 0xd0, 0x2b } }, { GCRY_CIPHER_AES, GCRY_CIPHER_MODE_CTR, "abcdefghijklmnop", 16, "1234567890123456", 16, /*[9]*/ { 0x9a, 0x48, 0x94, 0xd6, 0x50, 0x46, 0x81, 0xdb, 0x68, 0x34, 0x3b, 0xc5, 0x9e, 0x66, 0x94, 0x81, 0x98, 0xa0, 0xf9, 0xff } }, { GCRY_CIPHER_AES192, GCRY_CIPHER_MODE_CTR, "abcdefghijklmnopABCDEFG", 24, "1234567890123456", 16, /*[10]*/ { 0x2c, 0x2c, 0xd3, 0x75, 0x81, 0x2a, 0x59, 0x07, 0xeb, 0x08, 0xce, 0x28, 0x4c, 0x0c, 0x6a, 0xa8, 0x8f, 0xa3, 0x98, 0x7e } }, { GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CTR, "abcdefghijklmnopABCDEFGHIJKLMNOP", 32, "1234567890123456", 16, /*[11]*/ { 0x64, 0xce, 0x73, 0x03, 0xc7, 0x89, 0x99, 0x1f, 0xf1, 0xce, 0xfe, 0xfb, 0xb9, 0x42, 0x30, 0xdf, 0xbb, 0x68, 0x6f, 0xd3 } }, { GCRY_CIPHER_AES, GCRY_CIPHER_MODE_ECB, "abcdefghijklmnop", 16, "1234567890123456", 16, /*[12]*/ { 0x51, 0xae, 0xf5, 0xac, 0x22, 0xa0, 0xba, 0x11, 0xc5, 0xaa, 0xb4, 0x70, 0x99, 0xce, 0x18, 0x08, 0x12, 0x9b, 0xb1, 0xc5 } }, { GCRY_CIPHER_AES192, GCRY_CIPHER_MODE_ECB, "abcdefghijklmnopABCDEFG", 24, "1234567890123456", 16, /*[13]*/ { 0x57, 0x91, 0xea, 0x48, 0xd8, 0xbf, 0x9e, 0xc1, 0xae, 0x33, 0xb3, 0xfd, 0xf7, 0x7a, 0xeb, 0x30, 0xb1, 0x62, 0x0d, 0x82 } }, { GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_ECB, "abcdefghijklmnopABCDEFGHIJKLMNOP", 32, "1234567890123456", 16, /*[14]*/ { 0x2d, 0x71, 0x54, 0xb9, 0xc5, 0x28, 0x76, 0xff, 0x76, 0xb5, 0x99, 0x37, 0x99, 0x9d, 0xf7, 0x10, 0x6d, 0x86, 0x4f, 0x3f } }, { GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_XTS, "abcdefghijklmnopABCDEFGHIJKLMNOP", 32, "1234567890123456", 16, /*[15]*/ { 0x71, 0x46, 0x40, 0xb0, 0xed, 0x6f, 0xc4, 0x82, 0x2b, 0x3f, 0xb6, 0xf7, 0x81, 0x08, 0x4c, 0x8b, 0xc1, 0x66, 0x4c, 0x1b } }, { GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_XTS, "abcdefghijklmnopABCDEFGHIJKLMNOP_abcdefghijklmnopABCDEFGHIJKLMNO", 64, "1234567890123456", 16, /*[16]*/ { 0x8e, 0xbc, 0xa5, 0x21, 0x0a, 0x4b, 0x53, 0x14, 0x79, 0x81, 0x25, 0xad, 0x24, 0x45, 0x98, 0xbd, 0x9f, 0x27, 0x5f, 0x01 } } }; gcry_cipher_hd_t hde = NULL; gcry_cipher_hd_t hdd = NULL; unsigned char *buffer_base, *outbuf_base; /* Allocated buffers. */ unsigned char *buffer, *outbuf; /* Aligned buffers. */ size_t buflen; unsigned char hash[20]; int i, j, keylen, blklen; gcry_error_t err = 0; if (verbose) fprintf (stderr, "Starting bulk cipher checks.\n"); buflen = 16*100; /* We check a 1600 byte buffer. */ buffer_base = gcry_xmalloc (buflen+16); buffer = buffer_base + (16 - ((size_t)buffer_base & 0x0f)); outbuf_base = gcry_xmalloc (buflen+16); outbuf = outbuf_base + (16 - ((size_t)outbuf_base & 0x0f)); for (i = 0; i < DIM (tv); i++) { if (verbose) fprintf (stderr, " checking bulk encryption for %s [%i], mode %d\n", gcry_cipher_algo_name (tv[i].algo), tv[i].algo, tv[i].mode); err = gcry_cipher_open (&hde, tv[i].algo, tv[i].mode, 0); if (!err) err = gcry_cipher_open (&hdd, tv[i].algo, tv[i].mode, 0); if (err) { fail ("gcry_cipher_open failed: %s\n", gpg_strerror (err)); goto leave; } keylen = gcry_cipher_get_algo_keylen(tv[i].algo); if (!keylen) { fail ("gcry_cipher_get_algo_keylen failed\n"); goto leave; } err = gcry_cipher_setkey (hde, tv[i].key, tv[i].keylen); if (!err) err = gcry_cipher_setkey (hdd, tv[i].key, tv[i].keylen); if (err) { fail ("gcry_cipher_setkey failed: %s\n", gpg_strerror (err)); goto leave; } blklen = gcry_cipher_get_algo_blklen(tv[i].algo); if (!blklen) { fail ("gcry_cipher_get_algo_blklen failed\n"); goto leave; } err = gcry_cipher_setiv (hde, tv[i].iv, tv[i].ivlen); if (!err) err = gcry_cipher_setiv (hdd, tv[i].iv, tv[i].ivlen); if (err) { fail ("gcry_cipher_setiv failed: %s\n", gpg_strerror (err)); goto leave; } /* Fill the buffer with our test pattern. */ for (j=0; j < buflen; j++) buffer[j] = ((j & 0xff) ^ ((j >> 8) & 0xff)); err = gcry_cipher_encrypt (hde, outbuf, buflen, buffer, buflen); if (err) { fail ("gcry_cipher_encrypt (algo %d, mode %d) failed: %s\n", tv[i].algo, tv[i].mode, gpg_strerror (err)); goto leave; } gcry_md_hash_buffer (GCRY_MD_SHA1, hash, outbuf, buflen); #if 0 printf ("/*[%d]*/\n", i); fputs (" {", stdout); for (j=0; j < 20; j++) printf (" 0x%02x%c%s", hash[j], j==19? ' ':',', j == 9? "\n ":""); puts ("}"); #endif if (memcmp (hash, tv[i].t1_hash, 20)) fail ("encrypt mismatch (algo %d, mode %d)\n", tv[i].algo, tv[i].mode); err = gcry_cipher_decrypt (hdd, outbuf, buflen, NULL, 0); if (err) { fail ("gcry_cipher_decrypt (algo %d, mode %d) failed: %s\n", tv[i].algo, tv[i].mode, gpg_strerror (err)); goto leave; } if (memcmp (buffer, outbuf, buflen)) fail ("decrypt mismatch (algo %d, mode %d)\n", tv[i].algo, tv[i].mode); gcry_cipher_close (hde); hde = NULL; gcry_cipher_close (hdd); hdd = NULL; } if (verbose) fprintf (stderr, "Completed bulk cipher checks.\n"); leave: gcry_cipher_close (hde); gcry_cipher_close (hdd); gcry_free (buffer_base); gcry_free (outbuf_base); } static unsigned int get_algo_mode_blklen (int algo, int mode) { unsigned int blklen = gcry_cipher_get_algo_blklen(algo); /* Some modes override blklen. */ switch (mode) { case GCRY_CIPHER_MODE_STREAM: case GCRY_CIPHER_MODE_OFB: case GCRY_CIPHER_MODE_CTR: case GCRY_CIPHER_MODE_CCM: case GCRY_CIPHER_MODE_GCM: case GCRY_CIPHER_MODE_POLY1305: return 1; } return blklen; } static int check_one_cipher_core_reset (gcry_cipher_hd_t hd, int algo, int mode, int pass, int nplain) { static const unsigned char iv[8] = { 0, 1, 2, 3, 4, 5, 6, 7 }; u64 ctl_params[3]; int err; gcry_cipher_reset (hd); if (mode == GCRY_CIPHER_MODE_OCB || mode == GCRY_CIPHER_MODE_CCM) { err = gcry_cipher_setiv (hd, iv, sizeof(iv)); if (err) { fail ("pass %d, algo %d, mode %d, gcry_cipher_setiv failed: %s\n", pass, algo, mode, gpg_strerror (err)); gcry_cipher_close (hd); return -1; } } if (mode == GCRY_CIPHER_MODE_CCM) { ctl_params[0] = nplain; /* encryptedlen */ ctl_params[1] = 0; /* aadlen */ ctl_params[2] = 16; /* authtaglen */ err = gcry_cipher_ctl (hd, GCRYCTL_SET_CCM_LENGTHS, ctl_params, sizeof(ctl_params)); if (err) { fail ("pass %d, algo %d, mode %d, gcry_cipher_ctl " "GCRYCTL_SET_CCM_LENGTHS failed: %s\n", pass, algo, mode, gpg_strerror (err)); gcry_cipher_close (hd); return -1; } } return 0; } /* The core of the cipher check. In addition to the parameters passed to check_one_cipher it also receives the KEY and the plain data. PASS is printed with error messages. The function returns 0 on success. */ static int check_one_cipher_core (int algo, int mode, int flags, const char *key, size_t nkey, const unsigned char *plain, size_t nplain, int bufshift, int pass) { gcry_cipher_hd_t hd; unsigned char in_buffer[1040+1], out_buffer[1040+1]; unsigned char enc_result[1040]; unsigned char *in, *out; int keylen; gcry_error_t err = 0; unsigned int blklen; unsigned int piecelen; unsigned int pos; blklen = get_algo_mode_blklen(algo, mode); assert (nkey == 64); assert (nplain == 1040); assert (sizeof(in_buffer) == nplain + 1); assert (sizeof(out_buffer) == sizeof(in_buffer)); assert (blklen > 0); if ((mode == GCRY_CIPHER_MODE_CBC && (flags & GCRY_CIPHER_CBC_CTS)) || mode == GCRY_CIPHER_MODE_XTS) { /* Input cannot be split in to multiple operations with CTS . */ blklen = nplain; } if (!bufshift) { in = in_buffer; out = out_buffer; } else if (bufshift == 1) { in = in_buffer+1; out = out_buffer; } else if (bufshift == 2) { in = in_buffer+1; out = out_buffer+1; } else { in = in_buffer; out = out_buffer+1; } keylen = gcry_cipher_get_algo_keylen (algo); if (!keylen) { fail ("pass %d, algo %d, mode %d, gcry_cipher_get_algo_keylen failed\n", pass, algo, mode); return -1; } if (keylen < 40 / 8 || keylen > 32) { fail ("pass %d, algo %d, mode %d, keylength problem (%d)\n", pass, algo, mode, keylen); return -1; } if (mode == GCRY_CIPHER_MODE_XTS) { keylen *= 2; } err = gcry_cipher_open (&hd, algo, mode, flags); if (err) { fail ("pass %d, algo %d, mode %d, gcry_cipher_open failed: %s\n", pass, algo, mode, gpg_strerror (err)); return -1; } err = gcry_cipher_setkey (hd, key, keylen); if (err) { fail ("pass %d, algo %d, mode %d, gcry_cipher_setkey failed: %s\n", pass, algo, mode, gpg_strerror (err)); gcry_cipher_close (hd); return -1; } if (check_one_cipher_core_reset (hd, algo, mode, pass, nplain) < 0) return -1; err = gcry_cipher_encrypt (hd, out, nplain, plain, nplain); if (err) { fail ("pass %d, algo %d, mode %d, gcry_cipher_encrypt failed: %s\n", pass, algo, mode, gpg_strerror (err)); gcry_cipher_close (hd); return -1; } memcpy (enc_result, out, nplain); if (check_one_cipher_core_reset (hd, algo, mode, pass, nplain) < 0) return -1; err = gcry_cipher_decrypt (hd, in, nplain, out, nplain); if (err) { fail ("pass %d, algo %d, mode %d, gcry_cipher_decrypt failed: %s\n", pass, algo, mode, gpg_strerror (err)); gcry_cipher_close (hd); return -1; } if (memcmp (plain, in, nplain)) fail ("pass %d, algo %d, mode %d, encrypt-decrypt mismatch\n", pass, algo, mode); /* Again, using in-place encryption. */ if (check_one_cipher_core_reset (hd, algo, mode, pass, nplain) < 0) return -1; memcpy (out, plain, nplain); err = gcry_cipher_encrypt (hd, out, nplain, NULL, 0); if (err) { fail ("pass %d, algo %d, mode %d, in-place, gcry_cipher_encrypt failed:" " %s\n", pass, algo, mode, gpg_strerror (err)); gcry_cipher_close (hd); return -1; } if (memcmp (enc_result, out, nplain)) fail ("pass %d, algo %d, mode %d, in-place, encrypt mismatch\n", pass, algo, mode); if (check_one_cipher_core_reset (hd, algo, mode, pass, nplain) < 0) return -1; err = gcry_cipher_decrypt (hd, out, nplain, NULL, 0); if (err) { fail ("pass %d, algo %d, mode %d, in-place, gcry_cipher_decrypt failed:" " %s\n", pass, algo, mode, gpg_strerror (err)); gcry_cipher_close (hd); return -1; } if (memcmp (plain, out, nplain)) fail ("pass %d, algo %d, mode %d, in-place, encrypt-decrypt mismatch\n", pass, algo, mode); /* Again, splitting encryption in multiple operations. */ if (check_one_cipher_core_reset (hd, algo, mode, pass, nplain) < 0) return -1; piecelen = blklen; pos = 0; while (pos < nplain) { if (piecelen > nplain - pos) piecelen = nplain - pos; err = gcry_cipher_encrypt (hd, out + pos, piecelen, plain + pos, piecelen); if (err) { fail ("pass %d, algo %d, mode %d, split-buffer (pos: %d, " "piecelen: %d), gcry_cipher_encrypt failed: %s\n", pass, algo, mode, pos, piecelen, gpg_strerror (err)); gcry_cipher_close (hd); return -1; } pos += piecelen; piecelen = piecelen * 2 - ((piecelen != blklen) ? blklen : 0); } if (memcmp (enc_result, out, nplain)) fail ("pass %d, algo %d, mode %d, split-buffer, encrypt mismatch\n", pass, algo, mode); if (check_one_cipher_core_reset (hd, algo, mode, pass, nplain) < 0) return -1; piecelen = blklen; pos = 0; while (pos < nplain) { if (piecelen > nplain - pos) piecelen = nplain - pos; err = gcry_cipher_decrypt (hd, in + pos, piecelen, out + pos, piecelen); if (err) { fail ("pass %d, algo %d, mode %d, split-buffer (pos: %d, " "piecelen: %d), gcry_cipher_decrypt failed: %s\n", pass, algo, mode, pos, piecelen, gpg_strerror (err)); gcry_cipher_close (hd); return -1; } pos += piecelen; piecelen = piecelen * 2 - ((piecelen != blklen) ? blklen : 0); } if (memcmp (plain, in, nplain)) fail ("pass %d, algo %d, mode %d, split-buffer, encrypt-decrypt mismatch\n", pass, algo, mode); /* Again, using in-place encryption and splitting encryption in multiple * operations. */ if (check_one_cipher_core_reset (hd, algo, mode, pass, nplain) < 0) return -1; piecelen = blklen; pos = 0; while (pos < nplain) { if (piecelen > nplain - pos) piecelen = nplain - pos; memcpy (out + pos, plain + pos, piecelen); err = gcry_cipher_encrypt (hd, out + pos, piecelen, NULL, 0); if (err) { fail ("pass %d, algo %d, mode %d, in-place split-buffer (pos: %d, " "piecelen: %d), gcry_cipher_encrypt failed: %s\n", pass, algo, mode, pos, piecelen, gpg_strerror (err)); gcry_cipher_close (hd); return -1; } pos += piecelen; piecelen = piecelen * 2 - ((piecelen != blklen) ? blklen : 0); } if (memcmp (enc_result, out, nplain)) fail ("pass %d, algo %d, mode %d, in-place split-buffer, encrypt mismatch\n", pass, algo, mode); if (check_one_cipher_core_reset (hd, algo, mode, pass, nplain) < 0) return -1; piecelen = blklen; pos = 0; while (pos < nplain) { if (piecelen > nplain - pos) piecelen = nplain - pos; err = gcry_cipher_decrypt (hd, out + pos, piecelen, NULL, 0); if (err) { fail ("pass %d, algo %d, mode %d, in-place split-buffer (pos: %d, " "piecelen: %d), gcry_cipher_decrypt failed: %s\n", pass, algo, mode, pos, piecelen, gpg_strerror (err)); gcry_cipher_close (hd); return -1; } pos += piecelen; piecelen = piecelen * 2 - ((piecelen != blklen) ? blklen : 0); } if (memcmp (plain, out, nplain)) fail ("pass %d, algo %d, mode %d, in-place split-buffer, encrypt-decrypt" " mismatch\n", pass, algo, mode); gcry_cipher_close (hd); return 0; } static void check_one_cipher (int algo, int mode, int flags) { char key[64+1]; unsigned char plain[1040+1]; int bufshift, i; for (bufshift=0; bufshift < 4; bufshift++) { /* Pass 0: Standard test. */ memcpy (key, "0123456789abcdef.,;/[]{}-=ABCDEF_" "0123456789abcdef.,;/[]{}-=ABCDEF", 64); memcpy (plain, "foobar42FOOBAR17", 16); for (i = 16; i < 1040; i += 16) { memcpy (&plain[i], &plain[i-16], 16); if (!++plain[i+7]) plain[i+6]++; if (!++plain[i+15]) plain[i+14]++; } if (check_one_cipher_core (algo, mode, flags, key, 64, plain, 1040, bufshift, 0+10*bufshift)) return; /* Pass 1: Key not aligned. */ memmove (key+1, key, 64); if (check_one_cipher_core (algo, mode, flags, key+1, 64, plain, 1040, bufshift, 1+10*bufshift)) return; /* Pass 2: Key not aligned and data not aligned. */ memmove (plain+1, plain, 1040); if (check_one_cipher_core (algo, mode, flags, key+1, 64, plain+1, 1040, bufshift, 2+10*bufshift)) return; /* Pass 3: Key aligned and data not aligned. */ memmove (key, key+1, 64); if (check_one_cipher_core (algo, mode, flags, key, 64, plain+1, 1040, bufshift, 3+10*bufshift)) return; } return; } static void check_ciphers (void) { static const int algos[] = { #if USE_BLOWFISH GCRY_CIPHER_BLOWFISH, #endif #if USE_DES GCRY_CIPHER_DES, GCRY_CIPHER_3DES, #endif #if USE_CAST5 GCRY_CIPHER_CAST5, #endif #if USE_AES GCRY_CIPHER_AES, GCRY_CIPHER_AES192, GCRY_CIPHER_AES256, #endif #if USE_TWOFISH GCRY_CIPHER_TWOFISH, GCRY_CIPHER_TWOFISH128, #endif #if USE_SERPENT GCRY_CIPHER_SERPENT128, GCRY_CIPHER_SERPENT192, GCRY_CIPHER_SERPENT256, #endif #if USE_RFC2268 GCRY_CIPHER_RFC2268_40, #endif #if USE_SEED GCRY_CIPHER_SEED, #endif #if USE_CAMELLIA GCRY_CIPHER_CAMELLIA128, GCRY_CIPHER_CAMELLIA192, GCRY_CIPHER_CAMELLIA256, #endif #if USE_IDEA GCRY_CIPHER_IDEA, #endif #if USE_GOST28147 GCRY_CIPHER_GOST28147, #endif 0 }; static const int algos2[] = { #if USE_ARCFOUR GCRY_CIPHER_ARCFOUR, #endif #if USE_SALSA20 GCRY_CIPHER_SALSA20, GCRY_CIPHER_SALSA20R12, #endif #if USE_CHACHA20 GCRY_CIPHER_CHACHA20, #endif 0 }; int i; if (verbose) fprintf (stderr, "Starting Cipher checks.\n"); for (i = 0; algos[i]; i++) { if (gcry_cipher_test_algo (algos[i]) && in_fips_mode) { if (verbose) fprintf (stderr, " algorithm %d not available in fips mode\n", algos[i]); continue; } if (verbose) fprintf (stderr, " checking %s [%i]\n", gcry_cipher_algo_name (algos[i]), gcry_cipher_map_name (gcry_cipher_algo_name (algos[i]))); check_one_cipher (algos[i], GCRY_CIPHER_MODE_ECB, 0); check_one_cipher (algos[i], GCRY_CIPHER_MODE_CFB, 0); check_one_cipher (algos[i], GCRY_CIPHER_MODE_CFB8, 0); check_one_cipher (algos[i], GCRY_CIPHER_MODE_OFB, 0); check_one_cipher (algos[i], GCRY_CIPHER_MODE_CBC, 0); check_one_cipher (algos[i], GCRY_CIPHER_MODE_CBC, GCRY_CIPHER_CBC_CTS); check_one_cipher (algos[i], GCRY_CIPHER_MODE_CTR, 0); if (gcry_cipher_get_algo_blklen (algos[i]) == GCRY_CCM_BLOCK_LEN) check_one_cipher (algos[i], GCRY_CIPHER_MODE_CCM, 0); if (gcry_cipher_get_algo_blklen (algos[i]) == GCRY_GCM_BLOCK_LEN) check_one_cipher (algos[i], GCRY_CIPHER_MODE_GCM, 0); if (gcry_cipher_get_algo_blklen (algos[i]) == GCRY_OCB_BLOCK_LEN) check_one_cipher (algos[i], GCRY_CIPHER_MODE_OCB, 0); if (gcry_cipher_get_algo_blklen (algos[i]) == GCRY_XTS_BLOCK_LEN) check_one_cipher (algos[i], GCRY_CIPHER_MODE_XTS, 0); } for (i = 0; algos2[i]; i++) { if (gcry_cipher_test_algo (algos2[i]) && in_fips_mode) { if (verbose) fprintf (stderr, " algorithm %d not available in fips mode\n", algos2[i]); continue; } if (verbose) fprintf (stderr, " checking %s\n", gcry_cipher_algo_name (algos2[i])); check_one_cipher (algos2[i], GCRY_CIPHER_MODE_STREAM, 0); if (algos2[i] == GCRY_CIPHER_CHACHA20) check_one_cipher (algos2[i], GCRY_CIPHER_MODE_POLY1305, 0); } /* we have now run all cipher's selftests */ if (verbose) fprintf (stderr, "Completed Cipher checks.\n"); /* TODO: add some extra encryption to test the higher level functions */ } static void check_cipher_modes(void) { if (verbose) fprintf (stderr, "Starting Cipher Mode checks.\n"); check_aes128_cbc_cts_cipher (); check_cbc_mac_cipher (); check_ctr_cipher (); check_cfb_cipher (); check_ofb_cipher (); check_ccm_cipher (); check_gcm_cipher (); check_poly1305_cipher (); check_ocb_cipher (); check_xts_cipher (); check_gost28147_cipher (); check_stream_cipher (); check_stream_cipher_large_block (); if (verbose) fprintf (stderr, "Completed Cipher Mode checks.\n"); } static void fillbuf_count (char *buf, size_t buflen, unsigned char pos) { while (buflen--) *((unsigned char *)(buf++)) = pos++; } static void check_one_md (int algo, const char *data, int len, const char *expect, int elen, const char *key, int klen) { gcry_md_hd_t hd, hd2; unsigned char *p; int mdlen; int i; int xof = 0; gcry_error_t err = 0; err = gcry_md_open (&hd, algo, 0); if (err) { fail ("algo %d, gcry_md_open failed: %s\n", algo, gpg_strerror (err)); return; } mdlen = gcry_md_get_algo_dlen (algo); if (mdlen < 1 || mdlen > 500) { if (mdlen == 0 && (algo == GCRY_MD_SHAKE128 || algo == GCRY_MD_SHAKE256)) { xof = 1; } else { gcry_md_close (hd); fail ("algo %d, gcry_md_get_algo_dlen failed: %d\n", algo, mdlen); return; } } if (key && klen) { err = gcry_md_setkey (hd, key, klen); if (err) { gcry_md_close (hd); fail ("algo %d, gcry_md_setkey failed: %s\n", algo, gpg_strerror (err)); return; } } if ((*data == '!' && !data[1]) || /* hash one million times a "a" */ (*data == '?' && !data[1])) /* hash million byte data-set with byte pattern 0x00,0x01,0x02,... */ { char aaa[1000]; size_t left = 1000 * 1000; size_t startlen = 1; size_t piecelen = startlen; if (*data == '!') memset (aaa, 'a', 1000); /* Write in chuck with all sizes 1 to 1000 (500500 bytes) */ for (i = 1; i <= 1000 && left > 0; i++) { piecelen = i; if (piecelen > sizeof(aaa)) piecelen = sizeof(aaa); if (piecelen > left) piecelen = left; if (*data == '?') fillbuf_count(aaa, piecelen, 1000 * 1000 - left); gcry_md_write (hd, aaa, piecelen); left -= piecelen; } /* Write in odd size chunks so that we test the buffering. */ while (left > 0) { if (piecelen > sizeof(aaa)) piecelen = sizeof(aaa); if (piecelen > left) piecelen = left; if (*data == '?') fillbuf_count(aaa, piecelen, 1000 * 1000 - left); gcry_md_write (hd, aaa, piecelen); left -= piecelen; if (piecelen == sizeof(aaa)) piecelen = ++startlen; else piecelen = piecelen * 2 - ((piecelen != startlen) ? startlen : 0); } } else gcry_md_write (hd, data, len); err = gcry_md_copy (&hd2, hd); if (err) { fail ("algo %d, gcry_md_copy failed: %s\n", algo, gpg_strerror (err)); } gcry_md_close (hd); if (!xof) { p = gcry_md_read (hd2, algo); if (memcmp (p, expect, mdlen)) { printf ("computed: "); for (i = 0; i < mdlen; i++) printf ("%02x ", p[i] & 0xFF); printf ("\nexpected: "); for (i = 0; i < mdlen; i++) printf ("%02x ", expect[i] & 0xFF); printf ("\n"); fail ("algo %d, digest mismatch\n", algo); } } else { char buf[1000]; int outmax = sizeof(buf) > elen ? elen : sizeof(buf); err = gcry_md_copy (&hd, hd2); if (err) { fail ("algo %d, gcry_md_copy failed: %s\n", algo, gpg_strerror (err)); } err = gcry_md_extract(hd2, algo, buf, outmax); if (err) { fail ("algo %d, gcry_md_extract failed: %s\n", algo, gpg_strerror (err)); } if (memcmp (buf, expect, outmax)) { printf ("computed: "); for (i = 0; i < outmax; i++) printf ("%02x ", buf[i] & 0xFF); printf ("\nexpected: "); for (i = 0; i < outmax; i++) printf ("%02x ", expect[i] & 0xFF); printf ("\n"); fail ("algo %d, digest mismatch\n", algo); } memset(buf, 0, sizeof(buf)); /* Extract one byte at time. */ for (i = 0; i < outmax && !err; i++) err = gcry_md_extract(hd, algo, &buf[i], 1); if (err) { fail ("algo %d, gcry_md_extract failed: %s\n", algo, gpg_strerror (err)); } if (memcmp (buf, expect, outmax)) { printf ("computed: "); for (i = 0; i < outmax; i++) printf ("%02x ", buf[i] & 0xFF); printf ("\nexpected: "); for (i = 0; i < outmax; i++) printf ("%02x ", expect[i] & 0xFF); printf ("\n"); fail ("algo %d, digest mismatch\n", algo); } if (*data == '!' && !data[1]) { int crcalgo = GCRY_MD_RMD160; gcry_md_hd_t crc1, crc2; size_t startlen; size_t piecelen; size_t left; const unsigned char *p1, *p2; int crclen; crclen = gcry_md_get_algo_dlen (crcalgo); err = gcry_md_open (&crc1, crcalgo, 0); if (err) { fail ("algo %d, crcalgo: %d, gcry_md_open failed: %s\n", algo, crcalgo, gpg_strerror (err)); return; } err = gcry_md_open (&crc2, crcalgo, 0); if (err) { fail ("algo %d, crcalgo: %d, gcry_md_open failed: %s\n", algo, crcalgo, gpg_strerror (err)); return; } /* Extract large chucks, total 1000000 additional bytes. */ for (i = 0; i < 1000; i++) { err = gcry_md_extract(hd, algo, buf, 1000); if (!err) gcry_md_write(crc1, buf, 1000); } if (err) { fail ("algo %d, gcry_md_extract failed: %s\n", algo, gpg_strerror (err)); } /* Extract in odd size chunks, total 1000000 additional bytes. */ left = 1000 * 1000; startlen = 1; piecelen = startlen; while (!err && left > 0) { if (piecelen > sizeof(buf)) piecelen = sizeof(buf); if (piecelen > left) piecelen = left; err = gcry_md_extract (hd2, algo, buf, piecelen); if (!err) gcry_md_write(crc2, buf, piecelen); if (err) { fail ("algo %d, gcry_md_extract failed: %s\n", algo, gpg_strerror (err)); } left -= piecelen; if (piecelen == sizeof(buf)) piecelen = ++startlen; else piecelen = piecelen * 2 - ((piecelen != startlen) ? startlen : 0); } p1 = gcry_md_read (crc1, crcalgo); p2 = gcry_md_read (crc2, crcalgo); if (memcmp (p1, p2, crclen)) { printf ("computed: "); for (i = 0; i < crclen; i++) printf ("%02x ", p2[i] & 0xFF); printf ("\nexpected: "); for (i = 0; i < crclen; i++) printf ("%02x ", p1[i] & 0xFF); printf ("\n"); fail ("algo %d, large xof output mismatch\n", algo); } gcry_md_close (crc1); gcry_md_close (crc2); } gcry_md_close (hd); } gcry_md_close (hd2); } static void check_one_md_multi (int algo, const char *data, int len, const char *expect) { gpg_error_t err; gcry_buffer_t iov[3]; int iovcnt; char digest[64]; int mdlen; int i; mdlen = gcry_md_get_algo_dlen (algo); if (mdlen < 1 || mdlen > 64) { if (mdlen == 0 && (algo == GCRY_MD_SHAKE128 || algo == GCRY_MD_SHAKE256)) return; fail ("check_one_md_multi: algo %d, gcry_md_get_algo_dlen failed: %d\n", algo, mdlen); return; } if (*data == '!' && !data[1]) return; /* We can't do that here. */ if (*data == '?' && !data[1]) return; /* We can't do that here. */ memset (iov, 0, sizeof iov); iov[0].data = (void*)data; if (len) { iov[0].len = 1; len--; data++; } iovcnt = 1; if (len >= 4) { iov[iovcnt].data = (void*)data; iov[iovcnt].len = 4; iovcnt++; data += 4; len -= 4; } iov[iovcnt].data = (void*)data; iov[iovcnt].len = len; iovcnt++; assert (iovcnt <= DIM (iov)); err = gcry_md_hash_buffers (algo, 0, digest, iov, iovcnt); if (err) { fail ("check_one_md_multi: algo %d, gcry_hash_buffers failed: %s\n", algo, gpg_strerror (err)); return; } if (memcmp (digest, expect, mdlen)) { printf ("computed: "); for (i = 0; i < mdlen; i++) printf ("%02x ", digest[i] & 0xFF); printf ("\nexpected: "); for (i = 0; i < mdlen; i++) printf ("%02x ", expect[i] & 0xFF); printf ("\n"); fail ("check_one_md_multi: algo %d, digest mismatch\n", algo); } } static void check_digests (void) { static const char blake2_data_vector[] = "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" "\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f" "\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f" "\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f" "\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f" "\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f" "\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f" "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f" "\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f" "\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf" "\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf" "\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf" "\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf" "\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef" "\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff"; static const struct algos { int md; const char *data; const char *expect; int datalen; int expectlen; const char *key; int keylen; } algos[] = { { GCRY_MD_MD2, "", "\x83\x50\xe5\xa3\xe2\x4c\x15\x3d\xf2\x27\x5c\x9f\x80\x69\x27\x73" }, { GCRY_MD_MD2, "a", "\x32\xec\x01\xec\x4a\x6d\xac\x72\xc0\xab\x96\xfb\x34\xc0\xb5\xd1" }, { GCRY_MD_MD2, "message digest", "\xab\x4f\x49\x6b\xfb\x2a\x53\x0b\x21\x9f\xf3\x30\x31\xfe\x06\xb0" }, { GCRY_MD_MD4, "", "\x31\xD6\xCF\xE0\xD1\x6A\xE9\x31\xB7\x3C\x59\xD7\xE0\xC0\x89\xC0" }, { GCRY_MD_MD4, "a", "\xbd\xe5\x2c\xb3\x1d\xe3\x3e\x46\x24\x5e\x05\xfb\xdb\xd6\xfb\x24" }, { GCRY_MD_MD4, "message digest", "\xd9\x13\x0a\x81\x64\x54\x9f\xe8\x18\x87\x48\x06\xe1\xc7\x01\x4b" }, { GCRY_MD_MD5, "", "\xD4\x1D\x8C\xD9\x8F\x00\xB2\x04\xE9\x80\x09\x98\xEC\xF8\x42\x7E" }, { GCRY_MD_MD5, "a", "\x0C\xC1\x75\xB9\xC0\xF1\xB6\xA8\x31\xC3\x99\xE2\x69\x77\x26\x61" }, { GCRY_MD_MD5, "abc", "\x90\x01\x50\x98\x3C\xD2\x4F\xB0\xD6\x96\x3F\x7D\x28\xE1\x7F\x72" }, { GCRY_MD_MD5, "message digest", "\xF9\x6B\x69\x7D\x7C\xB7\x93\x8D\x52\x5A\x2F\x31\xAA\xF1\x61\xD0" }, { GCRY_MD_MD5, "Libgcrypt is free software; you can redistribute it and/or modif" "y it under the terms of the GNU Lesser general Public License as" " published by the Free Software Foundation; either version 2.1 o" "f the License, or (at your option) any later version.\nLibgcrypt" " is distributed in the hope that it will be useful, but WITHOUT " "ANY WARRANTY; without even the implied warranty of MERCHANTABILI" "TY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser Gene" "ral Public License for more details.", "\xc4\x1a\x5c\x0b\x44\x5f\xba\x1a\xda\xbc\xc0\x38\x0e\x0c\x9e\x33" }, { GCRY_MD_MD5, "!", "\x77\x07\xd6\xae\x4e\x02\x7c\x70\xee\xa2\xa9\x35\xc2\x29\x6f\x21" }, { GCRY_MD_MD5, "?", "\x5c\x72\x5c\xbc\x2d\xbb\xe1\x14\x81\x59\xe9\xd9\xcf\x90\x64\x8f" }, { GCRY_MD_SHA1, "abc", "\xA9\x99\x3E\x36\x47\x06\x81\x6A\xBA\x3E" "\x25\x71\x78\x50\xC2\x6C\x9C\xD0\xD8\x9D" }, { GCRY_MD_SHA1, "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "\x84\x98\x3E\x44\x1C\x3B\xD2\x6E\xBA\xAE" "\x4A\xA1\xF9\x51\x29\xE5\xE5\x46\x70\xF1" }, { GCRY_MD_SHA1, "!" /* kludge for "a"*1000000 */ , "\x34\xAA\x97\x3C\xD4\xC4\xDA\xA4\xF6\x1E" "\xEB\x2B\xDB\xAD\x27\x31\x65\x34\x01\x6F" }, { GCRY_MD_SHA1, "?" /* kludge for "\x00\x01\x02"..."\xfe\xff\x00\x01"... (length 1000000) */ , "\x5f\x8d\x3c\x4f\x12\xf0\x49\x9e\x28\x73" "\x79\xec\x97\x3b\x98\x4c\x94\x75\xaa\x8f" }, { GCRY_MD_SHA1, "Libgcrypt is free software; you can redistribute it and/or modif" "y it under the terms of the GNU Lesser general Public License as" " published by the Free Software Foundation; either version 2.1 o" "f the License, or (at your option) any later version.\nLibgcrypt" " is distributed in the hope that it will be useful, but WITHOUT " "ANY WARRANTY; without even the implied warranty of MERCHANTABILI" "TY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser Gene" "ral Public License for more details.", "\xf5\xd9\xcb\x66\x91\xb4\x7a\x7c\x60\x35\xe2\x1c\x38\x26\x52\x13" "\x8e\xd5\xe5\xdf" }, /* From RFC3874 */ { GCRY_MD_SHA224, "abc", "\x23\x09\x7d\x22\x34\x05\xd8\x22\x86\x42\xa4\x77\xbd\xa2\x55\xb3" "\x2a\xad\xbc\xe4\xbd\xa0\xb3\xf7\xe3\x6c\x9d\xa7" }, { GCRY_MD_SHA224, "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "\x75\x38\x8b\x16\x51\x27\x76\xcc\x5d\xba\x5d\xa1\xfd\x89\x01\x50" "\xb0\xc6\x45\x5c\xb4\xf5\x8b\x19\x52\x52\x25\x25" }, { GCRY_MD_SHA224, "!", "\x20\x79\x46\x55\x98\x0c\x91\xd8\xbb\xb4\xc1\xea\x97\x61\x8a\x4b" "\xf0\x3f\x42\x58\x19\x48\xb2\xee\x4e\xe7\xad\x67" }, { GCRY_MD_SHA224, "?", "\xfa\xb9\xf0\xdf\x12\xfe\xa1\x1a\x34\x78\x96\x31\xe6\x53\x48\xbf" "\x3b\xca\x70\x78\xf2\x44\xdf\x62\xab\x27\xb8\xda" }, { GCRY_MD_SHA224, "Libgcrypt is free software; you can redistribute it and/or modif" "y it under the terms of the GNU Lesser general Public License as" " published by the Free Software Foundation; either version 2.1 o" "f the License, or (at your option) any later version.\nLibgcrypt" " is distributed in the hope that it will be useful, but WITHOUT " "ANY WARRANTY; without even the implied warranty of MERCHANTABILI" "TY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser Gene" "ral Public License for more details.", "\x80\xf0\x60\x79\xb0\xe9\x65\xab\x8a\x76\xbf\x6e\x88\x64\x75\xe7" "\xfd\xf0\xc2\x4c\xf6\xf2\xa6\x01\xed\x50\x71\x08" }, { GCRY_MD_SHA256, "abc", "\xba\x78\x16\xbf\x8f\x01\xcf\xea\x41\x41\x40\xde\x5d\xae\x22\x23" "\xb0\x03\x61\xa3\x96\x17\x7a\x9c\xb4\x10\xff\x61\xf2\x00\x15\xad" }, { GCRY_MD_SHA256, "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "\x24\x8d\x6a\x61\xd2\x06\x38\xb8\xe5\xc0\x26\x93\x0c\x3e\x60\x39" "\xa3\x3c\xe4\x59\x64\xff\x21\x67\xf6\xec\xed\xd4\x19\xdb\x06\xc1" }, { GCRY_MD_SHA256, "!", "\xcd\xc7\x6e\x5c\x99\x14\xfb\x92\x81\xa1\xc7\xe2\x84\xd7\x3e\x67" "\xf1\x80\x9a\x48\xa4\x97\x20\x0e\x04\x6d\x39\xcc\xc7\x11\x2c\xd0" }, { GCRY_MD_SHA256, "?", "\x67\x87\x0d\xfc\x9c\x64\xe7\xaa\x27\x0a\x3f\x7e\x80\x51\xae\x65" "\xd2\x07\xf9\x3f\xc3\xdf\x04\xd7\x57\x2e\x63\x65\xaf\x69\xcd\x0d" }, { GCRY_MD_SHA256, "Libgcrypt is free software; you can redistribute it and/or modif" "y it under the terms of the GNU Lesser general Public License as" " published by the Free Software Foundation; either version 2.1 o" "f the License, or (at your option) any later version.\nLibgcrypt" " is distributed in the hope that it will be useful, but WITHOUT " "ANY WARRANTY; without even the implied warranty of MERCHANTABILI" "TY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser Gene" "ral Public License for more details.", "\xb0\x18\x70\x67\xb8\xac\x68\x50\xec\x95\x43\x77\xb5\x44\x5b\x0f" "\x2e\xbd\x40\xc9\xdc\x2a\x2c\x33\x8b\x53\xeb\x3e\x9e\x01\xd7\x02" }, { GCRY_MD_SHA384, "abc", "\xcb\x00\x75\x3f\x45\xa3\x5e\x8b\xb5\xa0\x3d\x69\x9a\xc6\x50\x07" "\x27\x2c\x32\xab\x0e\xde\xd1\x63\x1a\x8b\x60\x5a\x43\xff\x5b\xed" "\x80\x86\x07\x2b\xa1\xe7\xcc\x23\x58\xba\xec\xa1\x34\xc8\x25\xa7" }, { GCRY_MD_SHA384, "Libgcrypt is free software; you can redistribute it and/or modif" "y it under the terms of the GNU Lesser general Public License as" " published by the Free Software Foundation; either version 2.1 o" "f the License, or (at your option) any later version.\nLibgcrypt" " is distributed in the hope that it will be useful, but WITHOUT " "ANY WARRANTY; without even the implied warranty of MERCHANTABILI" "TY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser Gene" "ral Public License for more details.", "\xe4\x6d\xb4\x28\x33\x77\x99\x49\x94\x0f\xcf\x87\xc2\x2f\x30\xd6" "\x06\x24\x82\x9d\x80\x64\x8a\x07\xa1\x20\x8f\x5f\xf3\x85\xb3\xaa" "\x39\xb8\x61\x00\xfc\x7f\x18\xc6\x82\x23\x4b\x45\xfa\xf1\xbc\x69" }, { GCRY_MD_SHA384, "!", "\x9d\x0e\x18\x09\x71\x64\x74\xcb\x08\x6e\x83\x4e\x31\x0a\x4a\x1c" "\xed\x14\x9e\x9c\x00\xf2\x48\x52\x79\x72\xce\xc5\x70\x4c\x2a\x5b" "\x07\xb8\xb3\xdc\x38\xec\xc4\xeb\xae\x97\xdd\xd8\x7f\x3d\x89\x85" }, { GCRY_MD_SHA384, "?", "\xfa\x77\xbb\x86\x3a\xd5\xae\x88\xa9\x9c\x5e\xda\xb5\xc7\xcb\x40" "\xcd\xf4\x30\xef\xa8\x1b\x23\x7b\xa9\xde\xfd\x81\x12\xf6\x7e\xed" "\xa7\xd2\x27\x91\xd1\xbc\x76\x44\x57\x59\x71\x11\xe6\x8a\x2c\xde" }, { GCRY_MD_SHA512, "abc", "\xDD\xAF\x35\xA1\x93\x61\x7A\xBA\xCC\x41\x73\x49\xAE\x20\x41\x31" "\x12\xE6\xFA\x4E\x89\xA9\x7E\xA2\x0A\x9E\xEE\xE6\x4B\x55\xD3\x9A" "\x21\x92\x99\x2A\x27\x4F\xC1\xA8\x36\xBA\x3C\x23\xA3\xFE\xEB\xBD" "\x45\x4D\x44\x23\x64\x3C\xE8\x0E\x2A\x9A\xC9\x4F\xA5\x4C\xA4\x9F" }, { GCRY_MD_SHA512, "Libgcrypt is free software; you can redistribute it and/or modif" "y it under the terms of the GNU Lesser general Public License as" " published by the Free Software Foundation; either version 2.1 o" "f the License, or (at your option) any later version.\nLibgcrypt" " is distributed in the hope that it will be useful, but WITHOUT " "ANY WARRANTY; without even the implied warranty of MERCHANTABILI" "TY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser Gene" "ral Public License for more details.", "\x72\x8c\xde\xd8\xe4\xd7\xb6\xa5\x0f\xde\x6b\x4d\x33\xaf\x15\x19" "\xdd\xec\x62\x0f\xf7\x1a\x1e\x10\x32\x05\x02\xa6\xb0\x1f\x70\x37" "\xbc\xd7\x15\xed\x71\x6c\x78\x20\xc8\x54\x87\xd0\x66\x6a\x17\x83" "\x05\x61\x92\xbe\xcc\x8f\x3b\xbf\x11\x72\x22\x69\x23\x5b\x48\x5c" }, { GCRY_MD_SHA512, "!", "\xe7\x18\x48\x3d\x0c\xe7\x69\x64\x4e\x2e\x42\xc7\xbc\x15\xb4\x63" "\x8e\x1f\x98\xb1\x3b\x20\x44\x28\x56\x32\xa8\x03\xaf\xa9\x73\xeb" "\xde\x0f\xf2\x44\x87\x7e\xa6\x0a\x4c\xb0\x43\x2c\xe5\x77\xc3\x1b" "\xeb\x00\x9c\x5c\x2c\x49\xaa\x2e\x4e\xad\xb2\x17\xad\x8c\xc0\x9b" }, { GCRY_MD_SHA512, "?", "\x91\xe9\x42\x4e\xa9\xdc\x44\x01\x40\x64\xa4\x5a\x69\xcc\xac\xa3" "\x74\xee\x78\xeb\x79\x1f\x94\x38\x5b\x73\xef\xf8\xfd\x5d\x74\xd8" "\x51\x36\xfe\x63\x52\xde\x07\x70\x95\xd6\x78\x2b\x7b\x46\x8a\x2c" "\x30\x0f\x48\x0c\x74\x43\x06\xdb\xa3\x8d\x64\x3d\xe9\xa1\xa7\x72" }, { GCRY_MD_SHA3_224, "abc", "\xe6\x42\x82\x4c\x3f\x8c\xf2\x4a\xd0\x92\x34\xee\x7d\x3c\x76\x6f" "\xc9\xa3\xa5\x16\x8d\x0c\x94\xad\x73\xb4\x6f\xdf" }, { GCRY_MD_SHA3_256, "abc", "\x3a\x98\x5d\xa7\x4f\xe2\x25\xb2\x04\x5c\x17\x2d\x6b\xd3\x90\xbd" "\x85\x5f\x08\x6e\x3e\x9d\x52\x5b\x46\xbf\xe2\x45\x11\x43\x15\x32" }, { GCRY_MD_SHA3_384, "abc", "\xec\x01\x49\x82\x88\x51\x6f\xc9\x26\x45\x9f\x58\xe2\xc6\xad\x8d" "\xf9\xb4\x73\xcb\x0f\xc0\x8c\x25\x96\xda\x7c\xf0\xe4\x9b\xe4\xb2" "\x98\xd8\x8c\xea\x92\x7a\xc7\xf5\x39\xf1\xed\xf2\x28\x37\x6d\x25" }, { GCRY_MD_SHA3_512, "abc", "\xb7\x51\x85\x0b\x1a\x57\x16\x8a\x56\x93\xcd\x92\x4b\x6b\x09\x6e" "\x08\xf6\x21\x82\x74\x44\xf7\x0d\x88\x4f\x5d\x02\x40\xd2\x71\x2e" "\x10\xe1\x16\xe9\x19\x2a\xf3\xc9\x1a\x7e\xc5\x76\x47\xe3\x93\x40" "\x57\x34\x0b\x4c\xf4\x08\xd5\xa5\x65\x92\xf8\x27\x4e\xec\x53\xf0" }, { GCRY_MD_SHA3_224, "", "\x6b\x4e\x03\x42\x36\x67\xdb\xb7\x3b\x6e\x15\x45\x4f\x0e\xb1\xab" "\xd4\x59\x7f\x9a\x1b\x07\x8e\x3f\x5b\x5a\x6b\xc7" }, { GCRY_MD_SHA3_256, "", "\xa7\xff\xc6\xf8\xbf\x1e\xd7\x66\x51\xc1\x47\x56\xa0\x61\xd6\x62" "\xf5\x80\xff\x4d\xe4\x3b\x49\xfa\x82\xd8\x0a\x4b\x80\xf8\x43\x4a" }, { GCRY_MD_SHA3_384, "", "\x0c\x63\xa7\x5b\x84\x5e\x4f\x7d\x01\x10\x7d\x85\x2e\x4c\x24\x85" "\xc5\x1a\x50\xaa\xaa\x94\xfc\x61\x99\x5e\x71\xbb\xee\x98\x3a\x2a" "\xc3\x71\x38\x31\x26\x4a\xdb\x47\xfb\x6b\xd1\xe0\x58\xd5\xf0\x04" }, { GCRY_MD_SHA3_512, "", "\xa6\x9f\x73\xcc\xa2\x3a\x9a\xc5\xc8\xb5\x67\xdc\x18\x5a\x75\x6e" "\x97\xc9\x82\x16\x4f\xe2\x58\x59\xe0\xd1\xdc\xc1\x47\x5c\x80\xa6" "\x15\xb2\x12\x3a\xf1\xf5\xf9\x4c\x11\xe3\xe9\x40\x2c\x3a\xc5\x58" "\xf5\x00\x19\x9d\x95\xb6\xd3\xe3\x01\x75\x85\x86\x28\x1d\xcd\x26" }, { GCRY_MD_SHA3_224, "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlm" "nomnopnopq", "\x8a\x24\x10\x8b\x15\x4a\xda\x21\xc9\xfd\x55\x74\x49\x44\x79\xba" "\x5c\x7e\x7a\xb7\x6e\xf2\x64\xea\xd0\xfc\xce\x33" }, { GCRY_MD_SHA3_256, "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlm" "nomnopnopq", "\x41\xc0\xdb\xa2\xa9\xd6\x24\x08\x49\x10\x03\x76\xa8\x23\x5e\x2c" "\x82\xe1\xb9\x99\x8a\x99\x9e\x21\xdb\x32\xdd\x97\x49\x6d\x33\x76" }, { GCRY_MD_SHA3_384, "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlm" "nomnopnopq", "\x99\x1c\x66\x57\x55\xeb\x3a\x4b\x6b\xbd\xfb\x75\xc7\x8a\x49\x2e" "\x8c\x56\xa2\x2c\x5c\x4d\x7e\x42\x9b\xfd\xbc\x32\xb9\xd4\xad\x5a" "\xa0\x4a\x1f\x07\x6e\x62\xfe\xa1\x9e\xef\x51\xac\xd0\x65\x7c\x22" }, { GCRY_MD_SHA3_512, "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlm" "nomnopnopq", "\x04\xa3\x71\xe8\x4e\xcf\xb5\xb8\xb7\x7c\xb4\x86\x10\xfc\xa8\x18" "\x2d\xd4\x57\xce\x6f\x32\x6a\x0f\xd3\xd7\xec\x2f\x1e\x91\x63\x6d" "\xee\x69\x1f\xbe\x0c\x98\x53\x02\xba\x1b\x0d\x8d\xc7\x8c\x08\x63" "\x46\xb5\x33\xb4\x9c\x03\x0d\x99\xa2\x7d\xaf\x11\x39\xd6\xe7\x5e" }, { GCRY_MD_SHA3_224, "abcdefghbcdefghicdefghijdefghijkefghijklfghijk" "lmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu", "\x54\x3e\x68\x68\xe1\x66\x6c\x1a\x64\x36\x30\xdf\x77\x36\x7a\xe5" "\xa6\x2a\x85\x07\x0a\x51\xc1\x4c\xbf\x66\x5c\xbc" }, { GCRY_MD_SHA3_256, "abcdefghbcdefghicdefghijdefghijkefghijklfghijk" "lmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu", "\x91\x6f\x60\x61\xfe\x87\x97\x41\xca\x64\x69\xb4\x39\x71\xdf\xdb" "\x28\xb1\xa3\x2d\xc3\x6c\xb3\x25\x4e\x81\x2b\xe2\x7a\xad\x1d\x18" }, { GCRY_MD_SHA3_384, "abcdefghbcdefghicdefghijdefghijkefghijklfghijk" "lmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu", "\x79\x40\x7d\x3b\x59\x16\xb5\x9c\x3e\x30\xb0\x98\x22\x97\x47\x91" "\xc3\x13\xfb\x9e\xcc\x84\x9e\x40\x6f\x23\x59\x2d\x04\xf6\x25\xdc" "\x8c\x70\x9b\x98\xb4\x3b\x38\x52\xb3\x37\x21\x61\x79\xaa\x7f\xc7" }, { GCRY_MD_SHA3_512, "abcdefghbcdefghicdefghijdefghijkefghijklfghijk" "lmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu", "\xaf\xeb\xb2\xef\x54\x2e\x65\x79\xc5\x0c\xad\x06\xd2\xe5\x78\xf9" "\xf8\xdd\x68\x81\xd7\xdc\x82\x4d\x26\x36\x0f\xee\xbf\x18\xa4\xfa" "\x73\xe3\x26\x11\x22\x94\x8e\xfc\xfd\x49\x2e\x74\xe8\x2e\x21\x89" "\xed\x0f\xb4\x40\xd1\x87\xf3\x82\x27\x0c\xb4\x55\xf2\x1d\xd1\x85" }, { GCRY_MD_SHA3_224, "!", "\xd6\x93\x35\xb9\x33\x25\x19\x2e\x51\x6a\x91\x2e\x6d\x19\xa1\x5c" "\xb5\x1c\x6e\xd5\xc1\x52\x43\xe7\xa7\xfd\x65\x3c" }, { GCRY_MD_SHA3_256, "!", "\x5c\x88\x75\xae\x47\x4a\x36\x34\xba\x4f\xd5\x5e\xc8\x5b\xff\xd6" "\x61\xf3\x2a\xca\x75\xc6\xd6\x99\xd0\xcd\xcb\x6c\x11\x58\x91\xc1" }, { GCRY_MD_SHA3_384, "!", "\xee\xe9\xe2\x4d\x78\xc1\x85\x53\x37\x98\x34\x51\xdf\x97\xc8\xad" "\x9e\xed\xf2\x56\xc6\x33\x4f\x8e\x94\x8d\x25\x2d\x5e\x0e\x76\x84" "\x7a\xa0\x77\x4d\xdb\x90\xa8\x42\x19\x0d\x2c\x55\x8b\x4b\x83\x40" }, { GCRY_MD_SHA3_512, "!", "\x3c\x3a\x87\x6d\xa1\x40\x34\xab\x60\x62\x7c\x07\x7b\xb9\x8f\x7e" "\x12\x0a\x2a\x53\x70\x21\x2d\xff\xb3\x38\x5a\x18\xd4\xf3\x88\x59" "\xed\x31\x1d\x0a\x9d\x51\x41\xce\x9c\xc5\xc6\x6e\xe6\x89\xb2\x66" "\xa8\xaa\x18\xac\xe8\x28\x2a\x0e\x0d\xb5\x96\xc9\x0b\x0a\x7b\x87" }, { GCRY_MD_SHA3_224, "?", "\x1b\xd1\xc6\x12\x02\x35\x52\x8b\x44\x7e\x16\x39\x20\x05\xec\x67" "\x2d\x57\x20\xe0\x90\xc9\x78\x08\x86\x4f\x1b\xd0" }, { GCRY_MD_SHA3_256, "?", "\xfe\xb7\xf4\x76\x78\x97\x48\x2f\xe2\x29\x1b\x66\x85\xc1\x7b\x45" "\xc5\x08\xed\x82\x50\xcc\x5d\x99\x96\xd2\xc3\x82\x1a\xa8\xd4\xa7" }, { GCRY_MD_SHA3_384, "?", "\x45\x1f\x0b\x93\x4b\xca\x3e\x65\x93\xd4\xaa\x8c\x18\xc1\x04\x84" "\x12\xd5\x1e\x35\xe1\x05\xd9\x77\x3f\xc1\x08\x8b\x77\x36\xad\x4a" "\x33\x70\xaf\x49\x8b\xea\x4c\x5c\x52\xe7\x5b\xed\x31\x74\x57\x12" }, { GCRY_MD_SHA3_512, "?", "\xa2\xee\xb5\x6f\x2a\x87\xa5\xb3\x9b\xd9\x1c\xf0\xaa\xdf\xb1\xd5" "\xad\x0a\x1a\xaa\xd3\x63\x81\xcf\xb8\x7c\x36\xa7\x80\x3b\x03\xd6" "\x31\x5c\x5d\x33\x8e\x52\xb1\x42\x4d\x27\x1c\xa2\xa5\xf2\xc5\x97" "\x10\x12\xe5\xee\x86\xa3\xcc\xaf\x91\x7a\x94\x28\x65\xea\x66\xe3" }, { GCRY_MD_RMD160, "", "\x9c\x11\x85\xa5\xc5\xe9\xfc\x54\x61\x28" "\x08\x97\x7e\xe8\xf5\x48\xb2\x25\x8d\x31" }, { GCRY_MD_RMD160, "a", "\x0b\xdc\x9d\x2d\x25\x6b\x3e\xe9\xda\xae" "\x34\x7b\xe6\xf4\xdc\x83\x5a\x46\x7f\xfe" }, { GCRY_MD_RMD160, "abc", "\x8e\xb2\x08\xf7\xe0\x5d\x98\x7a\x9b\x04" "\x4a\x8e\x98\xc6\xb0\x87\xf1\x5a\x0b\xfc" }, { GCRY_MD_RMD160, "message digest", "\x5d\x06\x89\xef\x49\xd2\xfa\xe5\x72\xb8" "\x81\xb1\x23\xa8\x5f\xfa\x21\x59\x5f\x36" }, { GCRY_MD_RMD160, "Libgcrypt is free software; you can redistribute it and/or modif" "y it under the terms of the GNU Lesser general Public License as" " published by the Free Software Foundation; either version 2.1 o" "f the License, or (at your option) any later version.\nLibgcrypt" " is distributed in the hope that it will be useful, but WITHOUT " "ANY WARRANTY; without even the implied warranty of MERCHANTABILI" "TY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser Gene" "ral Public License for more details.", "\x06\x6d\x3c\x4e\xc9\xba\x89\x75\x16\x90\x96\x4e\xfd\x43\x07\xde" "\x04\xca\x69\x6b" }, { GCRY_MD_RMD160, "!", "\x52\x78\x32\x43\xc1\x69\x7b\xdb\xe1\x6d\x37\xf9\x7f\x68\xf0\x83" "\x25\xdc\x15\x28" }, { GCRY_MD_RMD160, "?", "\x68\x14\x86\x70\x3d\x51\x4e\x36\x68\x50\xf8\xb3\x00\x75\xda\x49" "\x0a\xaa\x2c\xf6" }, { GCRY_MD_CRC32, "", "\x00\x00\x00\x00" }, { GCRY_MD_CRC32, "foo", "\x8c\x73\x65\x21" }, { GCRY_MD_CRC32, "Libgcrypt is free software; you can redistribute it and/or modif" "y it under the terms of the GNU Lesser general Public License as" " published by the Free Software Foundation; either version 2.1 o" "f the License, or (at your option) any later version.\nLibgcrypt" " is distributed in the hope that it will be useful, but WITHOUT " "ANY WARRANTY; without even the implied warranty of MERCHANTABILI" "TY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser Gene" "ral Public License for more details.", "\x4A\x53\x7D\x67" }, { GCRY_MD_CRC32, "123456789", "\xcb\xf4\x39\x26" }, { GCRY_MD_CRC32, "!", "\xdc\x25\xbf\xbc" }, { GCRY_MD_CRC32, "?", "\x61\x82\x29\x1B" }, { GCRY_MD_CRC32_RFC1510, "", "\x00\x00\x00\x00" }, { GCRY_MD_CRC32_RFC1510, "foo", "\x73\x32\xbc\x33" }, { GCRY_MD_CRC32_RFC1510, "test0123456789", "\xb8\x3e\x88\xd6" }, { GCRY_MD_CRC32_RFC1510, "MASSACHVSETTS INSTITVTE OF TECHNOLOGY", "\xe3\x41\x80\xf7" }, { GCRY_MD_CRC32_RFC1510, "\x80\x00", "\x3b\x83\x98\x4b", 2 }, { GCRY_MD_CRC32_RFC1510, "\x00\x08", "\x0e\xdb\x88\x32", 2 }, { GCRY_MD_CRC32_RFC1510, "\x00\x80", "\xed\xb8\x83\x20", 2 }, { GCRY_MD_CRC32_RFC1510, "\x80", "\xed\xb8\x83\x20" }, { GCRY_MD_CRC32_RFC1510, "\x80\x00\x00\x00", "\xed\x59\xb6\x3b", 4 }, { GCRY_MD_CRC32_RFC1510, "\x00\x00\x00\x01", "\x77\x07\x30\x96", 4 }, { GCRY_MD_CRC32_RFC1510, "123456789", "\x2d\xfd\x2d\x88" }, { GCRY_MD_CRC32_RFC1510, "!", "\xce\x5c\x74\x22" }, { GCRY_MD_CRC32_RFC1510, "?", "\x73\xfb\xe2\x85" }, { GCRY_MD_CRC24_RFC2440, "", "\xb7\x04\xce" }, { GCRY_MD_CRC24_RFC2440, "foo", "\x4f\xc2\x55" }, { GCRY_MD_CRC24_RFC2440, "123456789", "\x21\xcf\x02" }, { GCRY_MD_CRC24_RFC2440, "!", "\xa5\xcb\x6b" }, { GCRY_MD_CRC24_RFC2440, "?", "\x7f\x67\x03" }, { GCRY_MD_TIGER, "", "\x24\xF0\x13\x0C\x63\xAC\x93\x32\x16\x16\x6E\x76" "\xB1\xBB\x92\x5F\xF3\x73\xDE\x2D\x49\x58\x4E\x7A" }, { GCRY_MD_TIGER, "abc", "\xF2\x58\xC1\xE8\x84\x14\xAB\x2A\x52\x7A\xB5\x41" "\xFF\xC5\xB8\xBF\x93\x5F\x7B\x95\x1C\x13\x29\x51" }, { GCRY_MD_TIGER, "Tiger", "\x9F\x00\xF5\x99\x07\x23\x00\xDD\x27\x6A\xBB\x38" "\xC8\xEB\x6D\xEC\x37\x79\x0C\x11\x6F\x9D\x2B\xDF" }, { GCRY_MD_TIGER, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefg" "hijklmnopqrstuvwxyz0123456789+-", "\x87\xFB\x2A\x90\x83\x85\x1C\xF7\x47\x0D\x2C\xF8" "\x10\xE6\xDF\x9E\xB5\x86\x44\x50\x34\xA5\xA3\x86" }, { GCRY_MD_TIGER, "ABCDEFGHIJKLMNOPQRSTUVWXYZ=abcdef" "ghijklmnopqrstuvwxyz+0123456789", "\x46\x7D\xB8\x08\x63\xEB\xCE\x48\x8D\xF1\xCD\x12" "\x61\x65\x5D\xE9\x57\x89\x65\x65\x97\x5F\x91\x97" }, { GCRY_MD_TIGER, "Tiger - A Fast New Hash Function, " "by Ross Anderson and Eli Biham", "\x0C\x41\x0A\x04\x29\x68\x86\x8A\x16\x71\xDA\x5A" "\x3F\xD2\x9A\x72\x5E\xC1\xE4\x57\xD3\xCD\xB3\x03" }, { GCRY_MD_TIGER, "Tiger - A Fast New Hash Function, " "by Ross Anderson and Eli Biham, proceedings of Fa" "st Software Encryption 3, Cambridge.", "\xEB\xF5\x91\xD5\xAF\xA6\x55\xCE\x7F\x22\x89\x4F" "\xF8\x7F\x54\xAC\x89\xC8\x11\xB6\xB0\xDA\x31\x93" }, { GCRY_MD_TIGER, "Tiger - A Fast New Hash Function, " "by Ross Anderson and Eli Biham, proceedings of Fa" "st Software Encryption 3, Cambridge, 1996.", "\x3D\x9A\xEB\x03\xD1\xBD\x1A\x63\x57\xB2\x77\x4D" "\xFD\x6D\x5B\x24\xDD\x68\x15\x1D\x50\x39\x74\xFC" }, { GCRY_MD_TIGER, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefgh" "ijklmnopqrstuvwxyz0123456789+-ABCDEFGHIJKLMNOPQRS" "TUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-", "\x00\xB8\x3E\xB4\xE5\x34\x40\xC5\x76\xAC\x6A\xAE" "\xE0\xA7\x48\x58\x25\xFD\x15\xE7\x0A\x59\xFF\xE4" }, { GCRY_MD_TIGER1, "", "\x32\x93\xAC\x63\x0C\x13\xF0\x24\x5F\x92\xBB\xB1" "\x76\x6E\x16\x16\x7A\x4E\x58\x49\x2D\xDE\x73\xF3" }, { GCRY_MD_TIGER1, "a", "\x77\xBE\xFB\xEF\x2E\x7E\xF8\xAB\x2E\xC8\xF9\x3B" "\xF5\x87\xA7\xFC\x61\x3E\x24\x7F\x5F\x24\x78\x09" }, { GCRY_MD_TIGER1, "abc", "\x2A\xAB\x14\x84\xE8\xC1\x58\xF2\xBF\xB8\xC5\xFF" "\x41\xB5\x7A\x52\x51\x29\x13\x1C\x95\x7B\x5F\x93" }, { GCRY_MD_TIGER1, "message digest", "\xD9\x81\xF8\xCB\x78\x20\x1A\x95\x0D\xCF\x30\x48" "\x75\x1E\x44\x1C\x51\x7F\xCA\x1A\xA5\x5A\x29\xF6" }, { GCRY_MD_TIGER1, "abcdefghijklmnopqrstuvwxyz", "\x17\x14\xA4\x72\xEE\xE5\x7D\x30\x04\x04\x12\xBF" "\xCC\x55\x03\x2A\x0B\x11\x60\x2F\xF3\x7B\xEE\xE9" }, { GCRY_MD_TIGER1, "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "\x0F\x7B\xF9\xA1\x9B\x9C\x58\xF2\xB7\x61\x0D\xF7" "\xE8\x4F\x0A\xC3\xA7\x1C\x63\x1E\x7B\x53\xF7\x8E" }, { GCRY_MD_TIGER1, "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789", "\x8D\xCE\xA6\x80\xA1\x75\x83\xEE\x50\x2B\xA3\x8A" "\x3C\x36\x86\x51\x89\x0F\xFB\xCC\xDC\x49\xA8\xCC" }, { GCRY_MD_TIGER1, "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890", "\x1C\x14\x79\x55\x29\xFD\x9F\x20\x7A\x95\x8F\x84" "\xC5\x2F\x11\xE8\x87\xFA\x0C\xAB\xDF\xD9\x1B\xFD" }, { GCRY_MD_TIGER1, "!", "\x6D\xB0\xE2\x72\x9C\xBE\xAD\x93\xD7\x15\xC6\xA7" "\xD3\x63\x02\xE9\xB3\xCE\xE0\xD2\xBC\x31\x4B\x41" }, { GCRY_MD_TIGER1, "Libgcrypt is free software; you can redistribute it and/or modif" "y it under the terms of the GNU Lesser general Public License as" " published by the Free Software Foundation; either version 2.1 o" "f the License, or (at your option) any later version.\nLibgcrypt" " is distributed in the hope that it will be useful, but WITHOUT " "ANY WARRANTY; without even the implied warranty of MERCHANTABILI" "TY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser Gene" "ral Public License for more details.", "\x60\xee\xdf\x95\x39\xc8\x44\x94\x64\xdc\xdf\x3d\x2e\x1c\xe5\x79" "\x6a\x95\xbd\x30\x68\x8c\x7e\xb8" }, { GCRY_MD_TIGER1, "?", "\x4b\xe2\x3f\x23\xf5\x34\xbe\xbf\x97\x42\x95\x80" "\x54\xe4\x6c\x12\x64\x85\x44\x0a\xa9\x49\x9b\x65" }, { GCRY_MD_TIGER2, "", "\x44\x41\xBE\x75\xF6\x01\x87\x73\xC2\x06\xC2\x27" "\x45\x37\x4B\x92\x4A\xA8\x31\x3F\xEF\x91\x9F\x41" }, { GCRY_MD_TIGER2, "a", "\x67\xE6\xAE\x8E\x9E\x96\x89\x99\xF7\x0A\x23\xE7" "\x2A\xEA\xA9\x25\x1C\xBC\x7C\x78\xA7\x91\x66\x36" }, { GCRY_MD_TIGER2, "abc", "\xF6\x8D\x7B\xC5\xAF\x4B\x43\xA0\x6E\x04\x8D\x78" "\x29\x56\x0D\x4A\x94\x15\x65\x8B\xB0\xB1\xF3\xBF" }, { GCRY_MD_TIGER2, "message digest", "\xE2\x94\x19\xA1\xB5\xFA\x25\x9D\xE8\x00\x5E\x7D" "\xE7\x50\x78\xEA\x81\xA5\x42\xEF\x25\x52\x46\x2D" }, { GCRY_MD_TIGER2, "abcdefghijklmnopqrstuvwxyz", "\xF5\xB6\xB6\xA7\x8C\x40\x5C\x85\x47\xE9\x1C\xD8" "\x62\x4C\xB8\xBE\x83\xFC\x80\x4A\x47\x44\x88\xFD" }, { GCRY_MD_TIGER2, "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "\xA6\x73\x7F\x39\x97\xE8\xFB\xB6\x3D\x20\xD2\xDF" "\x88\xF8\x63\x76\xB5\xFE\x2D\x5C\xE3\x66\x46\xA9" }, { GCRY_MD_TIGER2, "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789", "\xEA\x9A\xB6\x22\x8C\xEE\x7B\x51\xB7\x75\x44\xFC" "\xA6\x06\x6C\x8C\xBB\x5B\xBA\xE6\x31\x95\x05\xCD" }, { GCRY_MD_TIGER2, "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890" "1234567890", "\xD8\x52\x78\x11\x53\x29\xEB\xAA\x0E\xEC\x85\xEC" "\xDC\x53\x96\xFD\xA8\xAA\x3A\x58\x20\x94\x2F\xFF" }, { GCRY_MD_TIGER2, "!", "\xE0\x68\x28\x1F\x06\x0F\x55\x16\x28\xCC\x57\x15" "\xB9\xD0\x22\x67\x96\x91\x4D\x45\xF7\x71\x7C\xF4" }, { GCRY_MD_WHIRLPOOL, "", "\x19\xFA\x61\xD7\x55\x22\xA4\x66\x9B\x44\xE3\x9C\x1D\x2E\x17\x26" "\xC5\x30\x23\x21\x30\xD4\x07\xF8\x9A\xFE\xE0\x96\x49\x97\xF7\xA7" "\x3E\x83\xBE\x69\x8B\x28\x8F\xEB\xCF\x88\xE3\xE0\x3C\x4F\x07\x57" "\xEA\x89\x64\xE5\x9B\x63\xD9\x37\x08\xB1\x38\xCC\x42\xA6\x6E\xB3" }, { GCRY_MD_WHIRLPOOL, "a", "\x8A\xCA\x26\x02\x79\x2A\xEC\x6F\x11\xA6\x72\x06\x53\x1F\xB7\xD7" "\xF0\xDF\xF5\x94\x13\x14\x5E\x69\x73\xC4\x50\x01\xD0\x08\x7B\x42" "\xD1\x1B\xC6\x45\x41\x3A\xEF\xF6\x3A\x42\x39\x1A\x39\x14\x5A\x59" "\x1A\x92\x20\x0D\x56\x01\x95\xE5\x3B\x47\x85\x84\xFD\xAE\x23\x1A" }, { GCRY_MD_WHIRLPOOL, "?", "\x88\xf0\x78\x6d\x0d\x47\xe5\x32\x1f\x88\xb1\x48\x05\x53\x58\x7d" "\x19\x4b\x32\x9b\xf1\xfb\x17\xc5\x98\x3a\x87\xa2\x48\x61\x3d\x2b" "\xb2\xbc\x9f\x0d\xd2\x14\x37\x30\x55\x30\x91\xa7\xb8\x0c\x0f\x80" "\x7c\x7b\x94\xf6\x55\xf6\x0b\x12\x85\x0c\x8e\x6d\x17\x5b\x1e\x71" }, { GCRY_MD_WHIRLPOOL, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "\xDC\x37\xE0\x08\xCF\x9E\xE6\x9B\xF1\x1F\x00\xED\x9A\xBA\x26\x90" "\x1D\xD7\xC2\x8C\xDE\xC0\x66\xCC\x6A\xF4\x2E\x40\xF8\x2F\x3A\x1E" "\x08\xEB\xA2\x66\x29\x12\x9D\x8F\xB7\xCB\x57\x21\x1B\x92\x81\xA6" "\x55\x17\xCC\x87\x9D\x7B\x96\x21\x42\xC6\x5F\x5A\x7A\xF0\x14\x67" }, { GCRY_MD_WHIRLPOOL, "!", "\x0C\x99\x00\x5B\xEB\x57\xEF\xF5\x0A\x7C\xF0\x05\x56\x0D\xDF\x5D" "\x29\x05\x7F\xD8\x6B\x20\xBF\xD6\x2D\xEC\xA0\xF1\xCC\xEA\x4A\xF5" "\x1F\xC1\x54\x90\xED\xDC\x47\xAF\x32\xBB\x2B\x66\xC3\x4F\xF9\xAD" "\x8C\x60\x08\xAD\x67\x7F\x77\x12\x69\x53\xB2\x26\xE4\xED\x8B\x01" }, { GCRY_MD_WHIRLPOOL, "Libgcrypt is free software; you can redistribute it and/or modif" "y it under the terms of the GNU Lesser general Public License as" " published by the Free Software Foundation; either version 2.1 o" "f the License, or (at your option) any later version.\nLibgcrypt" " is distributed in the hope that it will be useful, but WITHOUT " "ANY WARRANTY; without even the implied warranty of MERCHANTABILI" "TY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser Gene" "ral Public License for more details.", "\xcd\x4a\xa4\xaf\xf6\x7f\xec\xce\xbb\x6c\xdf\x91\x96\xe1\xf3\xf6" "\x78\xe2\x8e\x3a\x76\xcf\x06\xc7\xa1\x20\x7b\x81\x32\x60\xf7\x8e" "\x68\x19\x62\x33\x4f\xe5\x0a\x24\xfb\x9e\x74\x03\x74\xe4\x61\x29" "\x6f\xb3\x13\xe6\x7e\xc2\x88\x99\x9e\xfb\xe7\x9d\x11\x30\x89\xd2" }, { GCRY_MD_GOSTR3411_94, "This is message, length=32 bytes", "\xB1\xC4\x66\xD3\x75\x19\xB8\x2E\x83\x19\x81\x9F\xF3\x25\x95\xE0" "\x47\xA2\x8C\xB6\xF8\x3E\xFF\x1C\x69\x16\xA8\x15\xA6\x37\xFF\xFA" }, { GCRY_MD_GOSTR3411_94, "Suppose the original message has length = 50 bytes", "\x47\x1A\xBA\x57\xA6\x0A\x77\x0D\x3A\x76\x13\x06\x35\xC1\xFB\xEA" "\x4E\xF1\x4D\xE5\x1F\x78\xB4\xAE\x57\xDD\x89\x3B\x62\xF5\x52\x08" }, { GCRY_MD_GOSTR3411_94, "", "\xCE\x85\xB9\x9C\xC4\x67\x52\xFF\xFE\xE3\x5C\xAB\x9A\x7B\x02\x78" "\xAB\xB4\xC2\xD2\x05\x5C\xFF\x68\x5A\xF4\x91\x2C\x49\x49\x0F\x8D" }, { GCRY_MD_GOSTR3411_94, "!", "\x5C\x00\xCC\xC2\x73\x4C\xDD\x33\x32\xD3\xD4\x74\x95\x76\xE3\xC1" "\xA7\xDB\xAF\x0E\x7E\xA7\x4E\x9F\xA6\x02\x41\x3C\x90\xA1\x29\xFA" }, { GCRY_MD_GOSTR3411_94, "Libgcrypt is free software; you can redistribute it and/or modif" "y it under the terms of the GNU Lesser general Public License as" " published by the Free Software Foundation; either version 2.1 o" "f the License, or (at your option) any later version.\nLibgcrypt" " is distributed in the hope that it will be useful, but WITHOUT " "ANY WARRANTY; without even the implied warranty of MERCHANTABILI" "TY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser Gene" "ral Public License for more details.", "\x00\x0c\x85\xc8\x54\xd2\x9a\x6e\x47\x2e\xff\xa4\xa2\xe7\xd0\x2e" "\x8a\xcc\x14\x53\xb4\x87\xc8\x5c\x95\x9a\x3e\x85\x8c\x7d\x6e\x0c" }, { GCRY_MD_STRIBOG512, "012345678901234567890123456789012345678901234567890123456789012", "\x1b\x54\xd0\x1a\x4a\xf5\xb9\xd5\xcc\x3d\x86\xd6\x8d\x28\x54\x62" "\xb1\x9a\xbc\x24\x75\x22\x2f\x35\xc0\x85\x12\x2b\xe4\xba\x1f\xfa" "\x00\xad\x30\xf8\x76\x7b\x3a\x82\x38\x4c\x65\x74\xf0\x24\xc3\x11" "\xe2\xa4\x81\x33\x2b\x08\xef\x7f\x41\x79\x78\x91\xc1\x64\x6f\x48" }, { GCRY_MD_STRIBOG256, "012345678901234567890123456789012345678901234567890123456789012", "\x9d\x15\x1e\xef\xd8\x59\x0b\x89\xda\xa6\xba\x6c\xb7\x4a\xf9\x27" "\x5d\xd0\x51\x02\x6b\xb1\x49\xa4\x52\xfd\x84\xe5\xe5\x7b\x55\x00" }, { GCRY_MD_STRIBOG512, "\xd1\xe5\x20\xe2\xe5\xf2\xf0\xe8\x2c\x20\xd1\xf2\xf0\xe8\xe1\xee" "\xe6\xe8\x20\xe2\xed\xf3\xf6\xe8\x2c\x20\xe2\xe5\xfe\xf2\xfa\x20" "\xf1\x20\xec\xee\xf0\xff\x20\xf1\xf2\xf0\xe5\xeb\xe0\xec\xe8\x20" "\xed\xe0\x20\xf5\xf0\xe0\xe1\xf0\xfb\xff\x20\xef\xeb\xfa\xea\xfb" "\x20\xc8\xe3\xee\xf0\xe5\xe2\xfb", "\x1e\x88\xe6\x22\x26\xbf\xca\x6f\x99\x94\xf1\xf2\xd5\x15\x69\xe0" "\xda\xf8\x47\x5a\x3b\x0f\xe6\x1a\x53\x00\xee\xe4\x6d\x96\x13\x76" "\x03\x5f\xe8\x35\x49\xad\xa2\xb8\x62\x0f\xcd\x7c\x49\x6c\xe5\xb3" "\x3f\x0c\xb9\xdd\xdc\x2b\x64\x60\x14\x3b\x03\xda\xba\xc9\xfb\x28" }, { GCRY_MD_STRIBOG256, "\xd1\xe5\x20\xe2\xe5\xf2\xf0\xe8\x2c\x20\xd1\xf2\xf0\xe8\xe1\xee" "\xe6\xe8\x20\xe2\xed\xf3\xf6\xe8\x2c\x20\xe2\xe5\xfe\xf2\xfa\x20" "\xf1\x20\xec\xee\xf0\xff\x20\xf1\xf2\xf0\xe5\xeb\xe0\xec\xe8\x20" "\xed\xe0\x20\xf5\xf0\xe0\xe1\xf0\xfb\xff\x20\xef\xeb\xfa\xea\xfb" "\x20\xc8\xe3\xee\xf0\xe5\xe2\xfb", "\x9d\xd2\xfe\x4e\x90\x40\x9e\x5d\xa8\x7f\x53\x97\x6d\x74\x05\xb0" "\xc0\xca\xc6\x28\xfc\x66\x9a\x74\x1d\x50\x06\x3c\x55\x7e\x8f\x50" }, #include "./sha3-224.h" #include "./sha3-256.h" #include "./sha3-384.h" #include "./sha3-512.h" { GCRY_MD_SHAKE128, "", "\x7F\x9C\x2B\xA4\xE8\x8F\x82\x7D\x61\x60\x45\x50\x76\x05\x85\x3E" "\xD7\x3B\x80\x93\xF6\xEF\xBC\x88\xEB\x1A\x6E\xAC\xFA\x66\xEF\x26" "\x3C\xB1\xEE\xA9\x88\x00\x4B\x93\x10\x3C\xFB\x0A\xEE\xFD\x2A\x68" "\x6E\x01\xFA\x4A\x58\xE8\xA3\x63\x9C\xA8\xA1\xE3\xF9\xAE\x57\xE2" "\x35\xB8\xCC\x87\x3C\x23\xDC\x62\xB8\xD2\x60\x16\x9A\xFA\x2F\x75" "\xAB\x91\x6A\x58\xD9\x74\x91\x88\x35\xD2\x5E\x6A\x43\x50\x85\xB2" "\xBA\xDF\xD6\xDF\xAA\xC3\x59\xA5\xEF\xBB\x7B\xCC\x4B\x59\xD5\x38" "\xDF\x9A\x04\x30\x2E\x10\xC8\xBC\x1C\xBF\x1A\x0B\x3A\x51\x20\xEA" "\x17\xCD\xA7\xCF\xAD\x76\x5F\x56\x23\x47\x4D\x36\x8C\xCC\xA8\xAF" "\x00\x07\xCD\x9F\x5E\x4C\x84\x9F\x16\x7A\x58\x0B\x14\xAA\xBD\xEF" "\xAE\xE7\xEE\xF4\x7C\xB0\xFC\xA9\x76\x7B\xE1\xFD\xA6\x94\x19\xDF" "\xB9\x27\xE9\xDF\x07\x34\x8B\x19\x66\x91\xAB\xAE\xB5\x80\xB3\x2D" "\xEF\x58\x53\x8B\x8D\x23\xF8\x77\x32\xEA\x63\xB0\x2B\x4F\xA0\xF4" "\x87\x33\x60\xE2\x84\x19\x28\xCD\x60\xDD\x4C\xEE\x8C\xC0\xD4\xC9" "\x22\xA9\x61\x88\xD0\x32\x67\x5C\x8A\xC8\x50\x93\x3C\x7A\xFF\x15" "\x33\xB9\x4C\x83\x4A\xDB\xB6\x9C\x61\x15\xBA\xD4\x69\x2D\x86\x19" "\xF9\x0B\x0C\xDF\x8A\x7B\x9C\x26\x40\x29\xAC\x18\x5B\x70\xB8\x3F" "\x28\x01\xF2\xF4\xB3\xF7\x0C\x59\x3E\xA3\xAE\xEB\x61\x3A\x7F\x1B" "\x1D\xE3\x3F\xD7\x50\x81\xF5\x92\x30\x5F\x2E\x45\x26\xED\xC0\x96" "\x31\xB1\x09\x58\xF4\x64\xD8\x89\xF3\x1B\xA0\x10\x25\x0F\xDA\x7F" "\x13\x68\xEC\x29\x67\xFC\x84\xEF\x2A\xE9\xAF\xF2\x68\xE0\xB1\x70" "\x0A\xFF\xC6\x82\x0B\x52\x3A\x3D\x91\x71\x35\xF2\xDF\xF2\xEE\x06" "\xBF\xE7\x2B\x31\x24\x72\x1D\x4A\x26\xC0\x4E\x53\xA7\x5E\x30\xE7" "\x3A\x7A\x9C\x4A\x95\xD9\x1C\x55\xD4\x95\xE9\xF5\x1D\xD0\xB5\xE9" "\xD8\x3C\x6D\x5E\x8C\xE8\x03\xAA\x62\xB8\xD6\x54\xDB\x53\xD0\x9B" "\x8D\xCF\xF2\x73\xCD\xFE\xB5\x73\xFA\xD8\xBC\xD4\x55\x78\xBE\xC2" "\xE7\x70\xD0\x1E\xFD\xE8\x6E\x72\x1A\x3F\x7C\x6C\xCE\x27\x5D\xAB" "\xE6\xE2\x14\x3F\x1A\xF1\x8D\xA7\xEF\xDD\xC4\xC7\xB7\x0B\x5E\x34" "\x5D\xB9\x3C\xC9\x36\xBE\xA3\x23\x49\x1C\xCB\x38\xA3\x88\xF5\x46" "\xA9\xFF\x00\xDD\x4E\x13\x00\xB9\xB2\x15\x3D\x20\x41\xD2\x05\xB4" "\x43\xE4\x1B\x45\xA6\x53\xF2\xA5\xC4\x49\x2C\x1A\xDD\x54\x45\x12" "\xDD\xA2\x52\x98\x33\x46\x2B\x71\xA4\x1A\x45\xBE\x97\x29\x0B\x6F", 0, 512, }, { GCRY_MD_SHAKE128, "\x5A\xAB\x62\x75\x6D\x30\x7A\x66\x9D\x14\x6A\xBA\x98\x8D\x90\x74" "\xC5\xA1\x59\xB3\xDE\x85\x15\x1A\x81\x9B\x11\x7C\xA1\xFF\x65\x97" "\xF6\x15\x6E\x80\xFD\xD2\x8C\x9C\x31\x76\x83\x51\x64\xD3\x7D\xA7" "\xDA\x11\xD9\x4E\x09\xAD\xD7\x70\xB6\x8A\x6E\x08\x1C\xD2\x2C\xA0" "\xC0\x04\xBF\xE7\xCD\x28\x3B\xF4\x3A\x58\x8D\xA9\x1F\x50\x9B\x27" "\xA6\x58\x4C\x47\x4A\x4A\x2F\x3E\xE0\xF1\xF5\x64\x47\x37\x92\x40" "\xA5\xAB\x1F\xB7\x7F\xDC\xA4\x9B\x30\x5F\x07\xBA\x86\xB6\x27\x56" "\xFB\x9E\xFB\x4F\xC2\x25\xC8\x68\x45\xF0\x26\xEA\x54\x20\x76\xB9" "\x1A\x0B\xC2\xCD\xD1\x36\xE1\x22\xC6\x59\xBE\x25\x9D\x98\xE5\x84" "\x1D\xF4\xC2\xF6\x03\x30\xD4\xD8\xCD\xEE\x7B\xF1\xA0\xA2\x44\x52" "\x4E\xEC\xC6\x8F\xF2\xAE\xF5\xBF\x00\x69\xC9\xE8\x7A\x11\xC6\xE5" "\x19\xDE\x1A\x40\x62\xA1\x0C\x83\x83\x73\x88\xF7\xEF\x58\x59\x8A" "\x38\x46\xF4\x9D\x49\x96\x82\xB6\x83\xC4\xA0\x62\xB4\x21\x59\x4F" "\xAF\xBC\x13\x83\xC9\x43\xBA\x83\xBD\xEF\x51\x5E\xFC\xF1\x0D", "\xF0\x71\x5D\xE3\x56\x92\xFD\x70\x12\x3D\xC6\x83\x68\xD0\xFE\xEC" "\x06\xA0\xC7\x4C\xF8\xAD\xB0\x5D\xDC\x25\x54\x87\xB1\xA8\xD4\xD1" "\x21\x3E\x9E\xAB\xAF\x41\xF1\x16\x17\x19\xD0\x65\xD7\x94\xB7\x50" "\xF8\x4B\xE3\x2A\x32\x34\xB4\xD5\x36\x46\x0D\x55\x20\x68\x8A\x5A" "\x79\xA1\x7A\x4B\xA8\x98\x7F\xCB\x61\xBF\x7D\xAA\x8B\x54\x7B\xF5" "\xC1\xCE\x36\xB5\x6A\x73\x25\x7D\xBB\xF1\xBA\xBB\x64\xF2\x49\xBD" "\xCE\xB6\x7B\xA1\xC8\x88\x37\x0A\x96\x3D\xFD\x6B\x6A\x2A\xDE\x2C" "\xEF\xD1\x4C\x32\x52\xCB\x37\x58\x52\x0F\x0C\x65\xF4\x52\x46\x82" "\x77\x24\x99\x46\x3A\xE1\xA3\x41\x80\x01\x83\xAA\x60\xEF\xA0\x51" "\x18\xA2\x82\x01\x74\x4F\x7B\xA0\xB0\xA3\x92\x8D\xD7\xC0\x26\x3F" "\xD2\x64\xB7\xCD\x7B\x2E\x2E\x09\xB3\x22\xBF\xCE\xA8\xEE\xD0\x42" "\x75\x79\x5B\xE7\xC0\xF0\x0E\x11\x38\x27\x37\x0D\x05\x1D\x50\x26" "\x95\x80\x30\x00\x05\xAC\x12\x88\xFE\xA6\xCD\x9A\xE9\xF4\xF3\x7C" "\xE0\xF8\xAC\xE8\xBF\x3E\xBE\x1D\x70\x56\x25\x59\x54\xC7\x61\x93" "\x1D\x3C\x42\xED\x62\xF7\xF1\xCE\x1B\x94\x5C\xDE\xCC\x0A\x74\x32" "\x2D\x7F\x64\xD6\x00\x4F\xF2\x16\x84\x14\x93\x07\x28\x8B\x44\x8E" "\x45\x43\x34\x75\xB1\xEA\x13\x14\xB0\x0F\x1F\xC4\x50\x08\x9A\x9D" "\x1F\x77\x10\xC6\xD7\x65\x2E\xCF\x65\x4F\x3B\x48\x7D\x02\x83\xD4" "\xD8\xA2\x8E\xFB\x50\x66\xC4\x25\x0D\x5A\xD6\x98\xE1\x5D\xBA\x88" "\xE9\x25\xE4\xDE\x99\xB6\x9B\xC3\x83\xAC\x80\x45\xB7\xF1\x02\x2A" "\xDD\x39\xD4\x43\x54\x6A\xE0\x92\x4F\x13\xF4\x89\x60\x96\xDF\xDF" "\x37\xCA\x72\x20\x79\x87\xC4\xA7\x70\x5A\x7A\xBE\x72\x4B\x7F\xA1" "\x0C\x90\x9F\x39\x25\x44\x9F\x01\x0D\x61\xE2\x07\xAD\xD9\x52\x19" "\x07\x1A\xCE\xED\xB9\xB9\xDC\xED\x32\xA9\xE1\x23\x56\x1D\x60\x82" "\xD4\x6A\xEF\xAE\x07\xEE\x1B\xD1\x32\x76\x5E\x3E\x51\x3C\x66\x50" "\x1B\x38\x7A\xB2\xEE\x09\xA0\x4A\xE6\x3E\x25\x80\x85\x17\xAF\xEA" "\x3E\x05\x11\x69\xCF\xD2\xFF\xF8\xC5\x85\x8E\x2D\x96\x23\x89\x7C" "\x9E\x85\x17\x5A\xC5\xA8\x63\x94\xCD\x0A\x32\xA0\xA6\x2A\x8F\x5D" "\x6C\xCC\xBF\x49\x3D\xAA\x43\xF7\x83\x62\xBB\xCA\x40\xAD\xF7\x33" "\xF8\x71\xE0\xC0\x09\x98\xD9\xBF\xD6\x88\x06\x56\x66\x6C\xD7\xBE" "\x4F\xE9\x89\x2C\x61\xDC\xD5\xCD\x23\xA5\xE4\x27\x7E\xEE\x8B\x4A" "\xFD\x29\xB6\x9B\xBA\x55\x66\x0A\x21\x71\x12\xFF\x6E\x34\x56\xB1", 223, 512, }, { GCRY_MD_SHAKE128, "!", "\x9d\x22\x2c\x79\xc4\xff\x9d\x09\x2c\xf6\xca\x86\x14\x3a\xa4\x11" "\xe3\x69\x97\x38\x08\xef\x97\x09\x32\x55\x82\x6c\x55\x72\xef\x58" "\x42\x4c\x4b\x5c\x28\x47\x5f\xfd\xcf\x98\x16\x63\x86\x7f\xec\x63" "\x21\xc1\x26\x2e\x38\x7b\xcc\xf8\xca\x67\x68\x84\xc4\xa9\xd0\xc1" "\x3b\xfa\x68\x69\x76\x3d\x5a\xe4\xbb\xc9\xb3\xcc\xd0\x9d\x1c\xa5" "\xea\x74\x46\x53\x8d\x69\xb3\xfb\x98\xc7\x2b\x59\xa2\xb4\x81\x7d" "\xb5\xea\xdd\x90\x11\xf9\x0f\xa7\x10\x91\x93\x1f\x81\x34\xf4\xf0" "\x0b\x56\x2e\x2f\xe1\x05\x93\x72\x70\x36\x1c\x19\x09\x86\x2a\xd4" "\x50\x46\xe3\x93\x2f\x5d\xd3\x11\xec\x72\xfe\xc5\xf8\xfb\x8f\x60" "\xb4\x5a\x3b\xee\x3f\x85\xbb\xf7\xfc\xed\xc6\xa5\x55\x67\x76\x48" "\xe0\x65\x4b\x38\x19\x41\xa8\x6b\xd3\xe5\x12\x65\x7b\x0d\x57\xa7" "\x99\x1f\xc4\x54\x3f\x89\xd8\x29\x04\x92\x22\x2c\xe4\xa3\x3e\x17" "\x60\x2b\x3b\x99\xc0\x09\xf7\x65\x5f\x87\x53\x5c\xda\xa3\x71\x6f" "\x58\xc4\x7b\x8a\x15\x7a\xd1\x95\xf0\x28\x09\xf2\x75\x00\xb9\x25" "\x49\x79\x31\x1c\x6b\xb4\x15\x96\x8c\xd1\x04\x31\x16\x9a\x27\xd5" "\xa8\xd6\x1e\x13\xa6\xb8\xb7\x7a\xf1\xf8\xb6\xdd\x2e\xef\xde\xa0" "\x40\x78\x96\x80\x49\x0b\x5e\xdc\xb1\xd3\xe5\x38\xa4\x66\xf7\x57" "\xad\x71\x8f\xe1\xfd\x9f\xae\xef\xa4\x72\x46\xad\x5e\x36\x7f\x87" "\xd3\xb4\x85\x0d\x44\x86\xeb\x21\x99\xe9\x4a\x79\x79\xe2\x09\x1a" "\xbc\xdf\x3b\xc1\x33\x79\xc8\x96\xdc\xeb\x79\xa8\xfd\x08\xf1\x10" "\x73\xf3\x3e\x3f\x99\x23\x22\xb3\x12\x02\xde\xe2\x34\x33\x0c\xf3" "\x30\x4a\x58\x8f\x0d\x59\xda\xe4\xe6\x3b\xa2\xac\x3c\xe6\x82\xcc" "\x19\xd4\xe3\x41\x67\x8c\xc3\xa6\x7a\x47\xc1\x13\xb4\xdb\x89\x0f" "\x30\xa9\x2a\xa0\x8a\x1f\x6d\xc8\xfb\x64\x63\xf8\x03\x8c\x2b\x40" "\xb2\x53\x00\x77\xb2\x36\xce\x88\xaf\xcc\xcd\xa0\x8a\xd6\xd7\x5e" "\xee\x18\x99\xb1\x0c\xd8\x00\xc2\xce\x53\x72\xbf\xf2\x2e\xe3\xa3" "\x39\xd4\xb9\xc1\xa2\xf5\xf4\xb8\x20\xf6\x87\xe5\x51\x9b\xd0\x5b" "\x1f\xc5\xda\x0e\xb4\x53\x36\x81\x4f\x48\x13\x2c\x64\x0e\x66\xc3" "\xa0\x2a\x22\xe6\x35\x98\xf9\x4f\x22\xf3\x51\x84\x11\x04\x46\xb6" "\x48\xcf\x84\x74\xf3\x0c\x43\xea\xd5\x83\x09\xfb\x25\x90\x16\x09" "\xe2\x41\x87\xe8\x01\xc8\x09\x56\x1a\x64\x80\x94\x50\xe6\x03\xc4" "\xa8\x03\x95\x25\xc4\x76\xb5\x8e\x32\xce\x2c\x47\xb3\x7d\xa5\x91", 0, 512, }, { GCRY_MD_SHAKE256, "", "\x46\xB9\xDD\x2B\x0B\xA8\x8D\x13\x23\x3B\x3F\xEB\x74\x3E\xEB\x24" "\x3F\xCD\x52\xEA\x62\xB8\x1B\x82\xB5\x0C\x27\x64\x6E\xD5\x76\x2F" "\xD7\x5D\xC4\xDD\xD8\xC0\xF2\x00\xCB\x05\x01\x9D\x67\xB5\x92\xF6" "\xFC\x82\x1C\x49\x47\x9A\xB4\x86\x40\x29\x2E\xAC\xB3\xB7\xC4\xBE" "\x14\x1E\x96\x61\x6F\xB1\x39\x57\x69\x2C\xC7\xED\xD0\xB4\x5A\xE3" "\xDC\x07\x22\x3C\x8E\x92\x93\x7B\xEF\x84\xBC\x0E\xAB\x86\x28\x53" "\x34\x9E\xC7\x55\x46\xF5\x8F\xB7\xC2\x77\x5C\x38\x46\x2C\x50\x10" "\xD8\x46\xC1\x85\xC1\x51\x11\xE5\x95\x52\x2A\x6B\xCD\x16\xCF\x86" "\xF3\xD1\x22\x10\x9E\x3B\x1F\xDD\x94\x3B\x6A\xEC\x46\x8A\x2D\x62" "\x1A\x7C\x06\xC6\xA9\x57\xC6\x2B\x54\xDA\xFC\x3B\xE8\x75\x67\xD6" "\x77\x23\x13\x95\xF6\x14\x72\x93\xB6\x8C\xEA\xB7\xA9\xE0\xC5\x8D" "\x86\x4E\x8E\xFD\xE4\xE1\xB9\xA4\x6C\xBE\x85\x47\x13\x67\x2F\x5C" "\xAA\xAE\x31\x4E\xD9\x08\x3D\xAB\x4B\x09\x9F\x8E\x30\x0F\x01\xB8" "\x65\x0F\x1F\x4B\x1D\x8F\xCF\x3F\x3C\xB5\x3F\xB8\xE9\xEB\x2E\xA2" "\x03\xBD\xC9\x70\xF5\x0A\xE5\x54\x28\xA9\x1F\x7F\x53\xAC\x26\x6B" "\x28\x41\x9C\x37\x78\xA1\x5F\xD2\x48\xD3\x39\xED\xE7\x85\xFB\x7F" "\x5A\x1A\xAA\x96\xD3\x13\xEA\xCC\x89\x09\x36\xC1\x73\xCD\xCD\x0F" "\xAB\x88\x2C\x45\x75\x5F\xEB\x3A\xED\x96\xD4\x77\xFF\x96\x39\x0B" "\xF9\xA6\x6D\x13\x68\xB2\x08\xE2\x1F\x7C\x10\xD0\x4A\x3D\xBD\x4E" "\x36\x06\x33\xE5\xDB\x4B\x60\x26\x01\xC1\x4C\xEA\x73\x7D\xB3\xDC" "\xF7\x22\x63\x2C\xC7\x78\x51\xCB\xDD\xE2\xAA\xF0\xA3\x3A\x07\xB3" "\x73\x44\x5D\xF4\x90\xCC\x8F\xC1\xE4\x16\x0F\xF1\x18\x37\x8F\x11" "\xF0\x47\x7D\xE0\x55\xA8\x1A\x9E\xDA\x57\xA4\xA2\xCF\xB0\xC8\x39" "\x29\xD3\x10\x91\x2F\x72\x9E\xC6\xCF\xA3\x6C\x6A\xC6\xA7\x58\x37" "\x14\x30\x45\xD7\x91\xCC\x85\xEF\xF5\xB2\x19\x32\xF2\x38\x61\xBC" "\xF2\x3A\x52\xB5\xDA\x67\xEA\xF7\xBA\xAE\x0F\x5F\xB1\x36\x9D\xB7" "\x8F\x3A\xC4\x5F\x8C\x4A\xC5\x67\x1D\x85\x73\x5C\xDD\xDB\x09\xD2" "\xB1\xE3\x4A\x1F\xC0\x66\xFF\x4A\x16\x2C\xB2\x63\xD6\x54\x12\x74" "\xAE\x2F\xCC\x86\x5F\x61\x8A\xBE\x27\xC1\x24\xCD\x8B\x07\x4C\xCD" "\x51\x63\x01\xB9\x18\x75\x82\x4D\x09\x95\x8F\x34\x1E\xF2\x74\xBD" "\xAB\x0B\xAE\x31\x63\x39\x89\x43\x04\xE3\x58\x77\xB0\xC2\x8A\x9B" "\x1F\xD1\x66\xC7\x96\xB9\xCC\x25\x8A\x06\x4A\x8F\x57\xE2\x7F\x2A", 0, 512, }, { GCRY_MD_SHAKE256, "\xB3\x2D\x95\xB0\xB9\xAA\xD2\xA8\x81\x6D\xE6\xD0\x6D\x1F\x86\x00" "\x85\x05\xBD\x8C\x14\x12\x4F\x6E\x9A\x16\x3B\x5A\x2A\xDE\x55\xF8" "\x35\xD0\xEC\x38\x80\xEF\x50\x70\x0D\x3B\x25\xE4\x2C\xC0\xAF\x05" "\x0C\xCD\x1B\xE5\xE5\x55\xB2\x30\x87\xE0\x4D\x7B\xF9\x81\x36\x22" "\x78\x0C\x73\x13\xA1\x95\x4F\x87\x40\xB6\xEE\x2D\x3F\x71\xF7\x68" "\xDD\x41\x7F\x52\x04\x82\xBD\x3A\x08\xD4\xF2\x22\xB4\xEE\x9D\xBD" "\x01\x54\x47\xB3\x35\x07\xDD\x50\xF3\xAB\x42\x47\xC5\xDE\x9A\x8A" "\xBD\x62\xA8\xDE\xCE\xA0\x1E\x3B\x87\xC8\xB9\x27\xF5\xB0\x8B\xEB" "\x37\x67\x4C\x6F\x8E\x38\x0C\x04", "\xCC\x2E\xAA\x04\xEE\xF8\x47\x9C\xDA\xE8\x56\x6E\xB8\xFF\xA1\x10" "\x0A\x40\x79\x95\xBF\x99\x9A\xE9\x7E\xDE\x52\x66\x81\xDC\x34\x90" "\x61\x6F\x28\x44\x2D\x20\xDA\x92\x12\x4C\xE0\x81\x58\x8B\x81\x49" "\x1A\xED\xF6\x5C\xAA\xF0\xD2\x7E\x82\xA4\xB0\xE1\xD1\xCA\xB2\x38" "\x33\x32\x8F\x1B\x8D\xA4\x30\xC8\xA0\x87\x66\xA8\x63\x70\xFA\x84" "\x8A\x79\xB5\x99\x8D\xB3\xCF\xFD\x05\x7B\x96\xE1\xE2\xEE\x0E\xF2" "\x29\xEC\xA1\x33\xC1\x55\x48\xF9\x83\x99\x02\x04\x37\x30\xE4\x4B" "\xC5\x2C\x39\xFA\xDC\x1D\xDE\xEA\xD9\x5F\x99\x39\xF2\x20\xCA\x30" "\x06\x61\x54\x0D\xF7\xED\xD9\xAF\x37\x8A\x5D\x4A\x19\xB2\xB9\x3E" "\x6C\x78\xF4\x9C\x35\x33\x43\xA0\xB5\xF1\x19\x13\x2B\x53\x12\xD0" "\x04\x83\x1D\x01\x76\x9A\x31\x6D\x2F\x51\xBF\x64\xCC\xB2\x0A\x21" "\xC2\xCF\x7A\xC8\xFB\x6F\x6E\x90\x70\x61\x26\xBD\xAE\x06\x11\xDD" "\x13\x96\x2E\x8B\x53\xD6\xEA\xE2\x6C\x7B\x0D\x25\x51\xDA\xF6\x24" "\x8E\x9D\x65\x81\x73\x82\xB0\x4D\x23\x39\x2D\x10\x8E\x4D\x34\x43" "\xDE\x5A\xDC\x72\x73\xC7\x21\xA8\xF8\x32\x0E\xCF\xE8\x17\x7A\xC0" "\x67\xCA\x8A\x50\x16\x9A\x6E\x73\x00\x0E\xBC\xDC\x1E\x4E\xE6\x33" "\x9F\xC8\x67\xC3\xD7\xAE\xAB\x84\x14\x63\x98\xD7\xBA\xDE\x12\x1D" "\x19\x89\xFA\x45\x73\x35\x56\x4E\x97\x57\x70\xA3\xA0\x02\x59\xCA" "\x08\x70\x61\x08\x26\x1A\xA2\xD3\x4D\xE0\x0F\x8C\xAC\x7D\x45\xD3" "\x5E\x5A\xA6\x3E\xA6\x9E\x1D\x1A\x2F\x7D\xAB\x39\x00\xD5\x1E\x0B" "\xC6\x53\x48\xA2\x55\x54\x00\x70\x39\xA5\x2C\x3C\x30\x99\x80\xD1" "\x7C\xAD\x20\xF1\x15\x63\x10\xA3\x9C\xD3\x93\x76\x0C\xFE\x58\xF6" "\xF8\xAD\xE4\x21\x31\x28\x82\x80\xA3\x5E\x1D\xB8\x70\x81\x83\xB9" "\x1C\xFA\xF5\x82\x7E\x96\xB0\xF7\x74\xC4\x50\x93\xB4\x17\xAF\xF9" "\xDD\x64\x17\xE5\x99\x64\xA0\x1B\xD2\xA6\x12\xFF\xCF\xBA\x18\xA0" "\xF1\x93\xDB\x29\x7B\x9A\x6C\xC1\xD2\x70\xD9\x7A\xAE\x8F\x8A\x3A" "\x6B\x26\x69\x5A\xB6\x64\x31\xC2\x02\xE1\x39\xD6\x3D\xD3\xA2\x47" "\x78\x67\x6C\xEF\xE3\xE2\x1B\x02\xEC\x4E\x8F\x5C\xFD\x66\x58\x7A" "\x12\xB4\x40\x78\xFC\xD3\x9E\xEE\x44\xBB\xEF\x4A\x94\x9A\x63\xC0" "\xDF\xD5\x8C\xF2\xFB\x2C\xD5\xF0\x02\xE2\xB0\x21\x92\x66\xCF\xC0" "\x31\x81\x74\x86\xDE\x70\xB4\x28\x5A\x8A\x70\xF3\xD3\x8A\x61\xD3" "\x15\x5D\x99\xAA\xF4\xC2\x53\x90\xD7\x36\x45\xAB\x3E\x8D\x80\xF0", 136, 512, }, { GCRY_MD_SHAKE256, "!", "\x35\x78\xa7\xa4\xca\x91\x37\x56\x9c\xdf\x76\xed\x61\x7d\x31\xbb" "\x99\x4f\xca\x9c\x1b\xbf\x8b\x18\x40\x13\xde\x82\x34\xdf\xd1\x3a" "\x3f\xd1\x24\xd4\xdf\x76\xc0\xa5\x39\xee\x7d\xd2\xf6\xe1\xec\x34" "\x61\x24\xc8\x15\xd9\x41\x0e\x14\x5e\xb5\x61\xbc\xd9\x7b\x18\xab" "\x6c\xe8\xd5\x55\x3e\x0e\xab\x3d\x1f\x7d\xfb\x8f\x9d\xee\xfe\x16" "\x84\x7e\x21\x92\xf6\xf6\x1f\xb8\x2f\xb9\x0d\xde\x60\xb1\x90\x63" "\xc5\x6a\x4c\x55\xcd\xd7\xb6\x72\xb7\x5b\xf5\x15\xad\xbf\xe2\x04" "\x90\x3c\x8c\x00\x36\xde\x54\xa2\x99\x9a\x92\x0d\xe9\x0f\x66\xd7" "\xff\x6e\xc8\xe4\xc9\x3d\x24\xae\x34\x6f\xdc\xb3\xa5\xa5\xbd\x57" "\x39\xec\x15\xa6\xed\xdb\x5c\xe5\xb0\x2d\xa5\x30\x39\xfa\xc6\x3e" "\x19\x55\x5f\xaa\x2e\xdd\xc6\x93\xb1\xf0\xc2\xa6\xfc\xbe\x7c\x0a" "\x0a\x09\x1d\x0e\xe7\x00\xd7\x32\x2e\x4b\x0f\xf0\x95\x90\xde\x16" "\x64\x22\xf9\xea\xd5\xda\x4c\x99\x3d\x60\x5f\xe4\xd9\xc6\x34\x84" "\x3a\xa1\x78\xb1\x76\x72\xc6\x56\x8c\x8a\x2e\x62\xab\xeb\xea\x2c" "\x21\xc3\x02\xbd\x36\x6a\xd6\x98\x95\x9e\x1f\x6e\x43\x4a\xf1\x55" "\x56\x8b\x27\x34\xd8\x37\x9f\xcd\x3f\xfe\x64\x89\xba\xff\xa6\xd7" "\x11\x09\x44\x2e\x1b\x34\x4f\x13\x8a\x09\xca\xe3\xe2\xd3\x94\x2e" "\xee\x82\x8f\xc4\x7e\x64\xde\xb5\xe0\x0a\x02\x4a\xe1\xf2\xc0\x77" "\xe6\xb7\xb1\x33\xf6\xc1\xde\x91\x30\x92\xd4\xe8\x29\xec\xd2\xb2" "\xef\x28\xca\x80\x20\x82\x1e\x2b\x8b\xe5\x17\xd9\x3e\xd0\x88\x36" "\xf6\xf0\x66\xcc\x3d\x03\xb6\x25\xd8\x49\x7f\x29\xdb\xc1\xc3\x9e" "\x6f\xe4\x63\x22\x6f\x85\xc1\x28\xa2\xc2\x98\x88\x11\x2e\x06\xa9" "\x9c\x5d\x17\xb2\x5e\x90\x0d\x20\x4f\x39\x72\x31\xcd\xf7\x9c\x31" "\x34\x46\x53\x2d\xad\x07\xf4\xc0\xbd\x9f\xba\x1d\xd4\x13\xd8\xa7" "\xe6\xcb\xc0\xa0\x86\x2c\xc7\x69\x23\x9a\x89\xf9\xdb\x08\x5b\x78" "\xa0\x54\x59\x6a\xd7\x08\x0d\xdf\x96\x01\x9b\x73\x99\xb5\x03\x48" "\x0e\x5a\x65\xa2\x20\x8d\x74\x72\x4c\x98\x7d\x32\x5e\x9b\x0e\x82" "\xfe\xcd\x4f\x27\xf3\x13\x5b\x1d\x9e\x27\xb4\x8e\x69\xdd\x6f\x59" "\x62\xb8\xa6\x3b\x48\x92\x1e\xc8\xee\x53\x86\x9f\x1a\xc1\xc8\x18" "\x23\x87\xee\x0d\x6c\xfe\xf6\x53\xff\x8b\xf6\x05\xf1\x47\x04\xb7" "\x1b\xeb\x65\x53\xf2\x81\xfa\x75\x69\x48\xc4\x38\x49\x4b\x19\xb4" "\xee\x69\xa5\x43\x6b\x22\x2b\xc9\x88\xed\xa4\xac\x60\x00\x24\xc9", 0, 512, }, { GCRY_MD_BLAKE2B_512, "abc", "\xBA\x80\xA5\x3F\x98\x1C\x4D\x0D\x6A\x27\x97\xB6\x9F\x12\xF6\xE9" "\x4C\x21\x2F\x14\x68\x5A\xC4\xB7\x4B\x12\xBB\x6F\xDB\xFF\xA2\xD1" "\x7D\x87\xC5\x39\x2A\xAB\x79\x2D\xC2\x52\xD5\xDE\x45\x33\xCC\x95" "\x18\xD3\x8A\xA8\xDB\xF1\x92\x5A\xB9\x23\x86\xED\xD4\x00\x99\x23" }, { GCRY_MD_BLAKE2B_512, "\x00", "\x96\x1f\x6d\xd1\xe4\xdd\x30\xf6\x39\x01\x69\x0c\x51\x2e\x78\xe4" "\xb4\x5e\x47\x42\xed\x19\x7c\x3c\x5e\x45\xc5\x49\xfd\x25\xf2\xe4" "\x18\x7b\x0b\xc9\xfe\x30\x49\x2b\x16\xb0\xd0\xbc\x4e\xf9\xb0\xf3" "\x4c\x70\x03\xfa\xc0\x9a\x5e\xf1\x53\x2e\x69\x43\x02\x34\xce\xbd", 1, 64, "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" "\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f" "\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f", 64 }, #include "./blake2b.h" { GCRY_MD_BLAKE2B_160, "", "\xad\x75\xea\xd7\x9f\x71\x21\xd1\xf0\x8a\xfe\x59\x99\x27\xa5\xa3" "\x8b\xe1\xb1\x79", 0, 20, "\x65\x65\xcb\x30\xfb\x2c\x28\x54\x7c\xd0\x4c\x1d\x6a\x88\xf2\x7a" "\x6d\xe8\x55\x3d", 20 }, { GCRY_MD_BLAKE2B_160, "\x9c\x9c\x38", "\x82\x79\x9d\x7b\xe8\xf4\xd1\x69\xfb\x85\xe6\x63\x6a\x7b\x6c\x50" "\xa0\x1f\x70\xa2", 3, 20, "\x65\x65\xcb\x30\xfb\x2c\x28\x54\x7c\xd0\x4c\x1d\x6a\x88\xf2\x7a" "\x6d\xe8\x55\x3d", 20 }, { GCRY_MD_BLAKE2B_256, "", "\x89\x36\x29\x47\x52\x79\xdf\xd8\x2a\x84\x1a\x8f\x21\xa3\x72\xed" "\x30\xcc\xb8\xae\x34\x62\xe1\x90\x7f\x50\x66\x3f\x3c\x03\x66\x83", 0, 32, "\xd5\xd5\xab\x80\x2c\xad\xd9\x86\x60\xe7\x47\x2f\x77\xa6\x1d\xc4" "\xe2\xa6\x88\x2f\xb7\xe6\x9e\x85\x23\xa9\xcd\x76\x43\xb9\xfd\xb7", 32 }, { GCRY_MD_BLAKE2B_256, "\x9c\x9c\x38", "\x01\x6a\x18\xbb\x10\xe0\xc3\xa5\xe5\x9f\xce\xfd\x1a\x40\x7a\xb7" "\xf1\xc0\x36\x1b\x3f\x98\x34\x77\x42\x54\xd3\xf0\x4c\xda\x38\x98", 3, 32, "\xd5\xd5\xab\x80\x2c\xad\xd9\x86\x60\xe7\x47\x2f\x77\xa6\x1d\xc4" "\xe2\xa6\x88\x2f\xb7\xe6\x9e\x85\x23\xa9\xcd\x76\x43\xb9\xfd\xb7", 32 }, { GCRY_MD_BLAKE2B_384, "", "\xd7\x2c\x9b\x4a\x73\x4e\xb2\x07\xe9\xdd\xbf\xf0\x0b\x10\xc3\x70" "\xc8\x9d\x67\xd7\x96\xc3\xa7\xb9\x68\x15\xa9\x53\x92\x1b\xb2\x97" "\x59\xd2\x9d\x25\x63\xf3\xda\x4d\x7f\x3e\xa4\xa6\xe3\x4c\x32\x6b", 0, 48, "\xc0\xc0\x80\x41\xc2\x03\xc6\xca\x90\x5b\xeb\x46\x32\x79\xac\x26" "\xd3\xf9\xcc\xc6\x93\x5a\xed\x48\x35\x7d\xb3\x31\xe5\x16\xfb\x12" "\x0e\x21\x2f\x51\x80\xd1\x52\x24\x77\x9c\x13\xaf\xc3\x73\x37\xaa", 48 }, { GCRY_MD_BLAKE2B_384, "\x9c\x9c\x38", "\xef\x46\xfa\x54\xa2\xc2\x20\xda\x06\xa8\x4c\x77\x6e\x87\xdd\x0a" "\x21\xee\xb5\xe9\x40\x1a\x0a\x78\x11\x19\x74\x18\xfe\x92\x70\x15" "\x77\xd0\xa8\x53\x24\x48\xe8\xb8\x53\x6a\xa6\xc7\x42\xcd\x2c\x62", 3, 48, "\xc0\xc0\x80\x41\xc2\x03\xc6\xca\x90\x5b\xeb\x46\x32\x79\xac\x26" "\xd3\xf9\xcc\xc6\x93\x5a\xed\x48\x35\x7d\xb3\x31\xe5\x16\xfb\x12" "\x0e\x21\x2f\x51\x80\xd1\x52\x24\x77\x9c\x13\xaf\xc3\x73\x37\xaa", 48 }, { GCRY_MD_BLAKE2B_512, "", "\xd7\x4b\xf3\x1e\x5c\xe5\xd8\xa2\x5d\x09\x21\x52\x53\xca\xd2\xf8" "\xd2\xfd\xa9\x10\x09\x30\x16\x05\xa6\x8c\xc3\x86\x5b\xb7\x93\x5b" "\xca\xff\x6f\x2a\xf6\x43\xa7\x76\x99\xe8\x02\x61\xa1\xfd\x2c\x80" "\xe8\x37\xb5\x62\x32\xf7\xb1\x46\x43\x4a\xa7\x4d\x71\x18\xbb\x16", 0, 64, "\xab\xab\x56\x01\x58\x5a\xb3\x0d\xc1\xce\x8f\x5e\xee\x4d\x3b\x88" "\xc4\x4c\x11\x5e\x6f\xcd\x3d\x0a\x47\x52\x9a\xec\x86\x73\xfa\x6e" "\x68\xd6\x3f\x16\x55\x6b\xc1\x2d\xef\x1d\x0c\x29\x35\x5f\x94\xf3" "\x88\x7c\x04\x81\x86\x07\x8e\x95\x23\xb9\xdd\x97\x74\x0c\x80\x8c", 64 }, { GCRY_MD_BLAKE2B_512, "\x9c\x9c\x38", "\x70\xfc\x57\xe1\x49\x5f\xe4\x39\x0d\x38\xa1\xd3\x97\x05\xee\xf6" "\xaa\xbb\xd2\x64\xc7\xce\x66\x11\x8d\x0a\x87\xd4\x25\x94\xb3\x87" "\xdc\x50\x18\x8b\xba\x61\xf0\x91\xd6\xb3\x4f\xf5\x4e\x09\x1e\x70" "\x24\x01\x83\xcd\xb9\x21\x1f\x14\x39\x77\x5c\xc6\xe6\xe9\x35\x73", 3, 64, "\xab\xab\x56\x01\x58\x5a\xb3\x0d\xc1\xce\x8f\x5e\xee\x4d\x3b\x88" "\xc4\x4c\x11\x5e\x6f\xcd\x3d\x0a\x47\x52\x9a\xec\x86\x73\xfa\x6e" "\x68\xd6\x3f\x16\x55\x6b\xc1\x2d\xef\x1d\x0c\x29\x35\x5f\x94\xf3" "\x88\x7c\x04\x81\x86\x07\x8e\x95\x23\xb9\xdd\x97\x74\x0c\x80\x8c", 64 }, { GCRY_MD_BLAKE2B_512, "!", "\x98\xfb\x3e\xfb\x72\x06\xfd\x19\xeb\xf6\x9b\x6f\x31\x2c\xf7\xb6" "\x4e\x3b\x94\xdb\xe1\xa1\x71\x07\x91\x39\x75\xa7\x93\xf1\x77\xe1" "\xd0\x77\x60\x9d\x7f\xba\x36\x3c\xbb\xa0\x0d\x05\xf7\xaa\x4e\x4f" "\xa8\x71\x5d\x64\x28\x10\x4c\x0a\x75\x64\x3b\x0f\xf3\xfd\x3e\xaf" }, { GCRY_MD_BLAKE2B_512, "?", "\xae\x9c\xf5\x7a\xc2\xff\x7b\x37\x7a\x5b\xb5\xcc\x2e\x62\x92\x20" "\xa9\xba\x0a\x09\xc2\x2a\x0f\xdb\xd9\xa3\xae\xd6\x32\xc1\x72\x0e" "\x6d\x82\x9f\x74\x7f\xba\x12\xe8\x31\xa2\x45\x8d\xf0\x73\x4e\xe0" "\x12\x27\x52\xd3\xe2\x2c\x36\xc4\x42\x89\x3b\xcd\xd1\xbd\xd9\x08" }, { GCRY_MD_BLAKE2B_384, "?", "\x22\x66\x8e\x05\x81\x44\x52\xa5\x23\x84\xce\x67\xd4\xad\x0e\x03" "\xdf\xe7\x1a\xc1\x56\x9d\x95\x4a\xd2\x22\x7a\x70\x2a\xfe\x6c\x68" "\x5c\x7d\x65\x30\x2b\xc0\xde\xc6\xea\x72\x1e\xdd\x46\xdf\xb2\x08" }, { GCRY_MD_BLAKE2B_256, "?", "\xfa\x11\x30\xd8\xba\x8a\x4c\x5a\x0e\x6f\x4f\x4c\xd2\xd1\x38\x0c" "\xb9\x22\x2a\xbd\xf6\x20\x70\xf8\x02\x1b\x34\xdd\xd7\x24\x92\x1b" }, { GCRY_MD_BLAKE2B_160, "?", "\xe7\x86\x08\x31\xf8\x96\x8d\x64\x9b\xe0\x15\x68\x33\xf3\xbd\x2a" "\x5f\x0b\xdb\x40" }, { GCRY_MD_BLAKE2S_256, "abc", "\x50\x8C\x5E\x8C\x32\x7C\x14\xE2\xE1\xA7\x2B\xA3\x4E\xEB\x45\x2F" "\x37\x45\x8B\x20\x9E\xD6\x3A\x29\x4D\x99\x9B\x4C\x86\x67\x59\x82" }, #include "./blake2s.h" { GCRY_MD_BLAKE2S_128, "", "\x84\x89\x68\xb3\x59\x01\xe9\x57\x9a\x4d\xbf\x28\xdf\x99\xec\x23", 0, 16, "\xea\xea\xd5\xc0\x96\x56\xec\x43\x30\x73\xa3\x17\xbb\xd3\x8e\x62", 16 }, { GCRY_MD_BLAKE2S_128, "\x9c\x9c\x38", "\x2e\xbb\x18\x78\xda\x34\x05\xad\x98\x1a\x33\x06\x50\x35\xd3\x75", 3, 16, "\xea\xea\xd5\xc0\x96\x56\xec\x43\x30\x73\xa3\x17\xbb\xd3\x8e\x62", 16 }, { GCRY_MD_BLAKE2S_128, "\xab\xab\x56\x01\x58\x5a\xb3\x0d\xc1\xce\x8f\x5e\xee\x4d\x3b\x88" "\xc4\x4c\x11\x5e\x6f\xcd\x3d\x0a\x47\x52\x9a\xec\x86\x73\xfa\x6e" "\x68\xd6\x3f\x16\x55\x6b\xc1\x2d\xef\x1d\x0c\x29\x35\x5f\x94\xf3" "\x88\x7c\x04\x81\x86\x07\x8e\x95\x23\xb9\xdd\x97\x74\x0c\x80\x8c", "\x3c\xd4\xea\xd7\x88\x0b\x8e\x82\xde\x07\x9c\x1f\xad\x34\x17\xd4", 64, 16, "\xea\xea\xd5\xc0\x96\x56\xec\x43\x30\x73\xa3\x17\xbb\xd3\x8e\x62", 16 }, { GCRY_MD_BLAKE2S_128, "\x8a\x8a\x14\x9e\xb2\x50\x02\x52\x54\xa6\xfa\xa0\x9a\x3a\xd4\x0e" "\xe3\xf2\xd5\xc7\x9d\x64\x02\x66\x68\xcf\x38\x08\x41\x49\x8a\xd3" "\x5e\x32\x90\xc2\x53\x15\x68\x7e\xe6\x65\x4b\xb0\xfc\xad\xaa\x58" "\x02\x5b\x5e\xb9\x18\xd1\xe9\xbb\xa5\x61\x07\x68\x70\xd9\x49\x22" "\x6b", "\xee\x92\xc5\x25\x4c\x29\x7a\x88\xe6\x9a\x23\x69\x56\xb6\x7c\xee", 65, 16, "\xea\xea\xd5\xc0\x96\x56\xec\x43\x30\x73\xa3\x17\xbb\xd3\x8e\x62", 16 }, { GCRY_MD_BLAKE2S_160, "", "\x68\x64\x48\x80\x0c\x80\xc6\xd0\x4f\xb7\x3f\xc1\x7f\xa0\x8c\xa2" "\x39\x03\xe1\xe9", 0, 20, "\x65\x65\xcb\x30\xfb\x2c\x28\x54\x7c\xd0\x4c\x1d\x6a\x88\xf2\x7a" "\x6d\xe8\x55\x3d", 20 }, { GCRY_MD_BLAKE2S_160, "\x9c\x9c\x38", "\xba\xb3\x5b\x8c\x87\x04\x1a\x00\x24\x44\xa5\xca\x45\x13\x2d\x75" "\xef\xd3\x4c\xb9", 3, 20, "\x65\x65\xcb\x30\xfb\x2c\x28\x54\x7c\xd0\x4c\x1d\x6a\x88\xf2\x7a" "\x6d\xe8\x55\x3d", 20 }, { GCRY_MD_BLAKE2S_160, "\xab\xab\x56\x01\x58\x5a\xb3\x0d\xc1\xce\x8f\x5e\xee\x4d\x3b\x88" "\xc4\x4c\x11\x5e\x6f\xcd\x3d\x0a\x47\x52\x9a\xec\x86\x73\xfa\x6e" "\x68\xd6\x3f\x16\x55\x6b\xc1\x2d\xef\x1d\x0c\x29\x35\x5f\x94\xf3" "\x88\x7c\x04\x81\x86\x07\x8e\x95\x23\xb9\xdd\x97\x74\x0c\x80\x8c", "\xe8\xc3\xf1\xdb\x1c\xf8\xe9\xd1\xb5\x4a\x54\x0a\xdc\xe7\x18\x13" "\x0f\xf4\x12\x98", 64, 20, "\x65\x65\xcb\x30\xfb\x2c\x28\x54\x7c\xd0\x4c\x1d\x6a\x88\xf2\x7a" "\x6d\xe8\x55\x3d", 20 }, { GCRY_MD_BLAKE2S_160, "\x8a\x8a\x14\x9e\xb2\x50\x02\x52\x54\xa6\xfa\xa0\x9a\x3a\xd4\x0e" "\xe3\xf2\xd5\xc7\x9d\x64\x02\x66\x68\xcf\x38\x08\x41\x49\x8a\xd3" "\x5e\x32\x90\xc2\x53\x15\x68\x7e\xe6\x65\x4b\xb0\xfc\xad\xaa\x58" "\x02\x5b\x5e\xb9\x18\xd1\xe9\xbb\xa5\x61\x07\x68\x70\xd9\x49\x22" "\x6b", "\x59\x02\xf8\x38\x18\x77\x9c\xd8\x13\x40\x0f\xd6\xbb\x23\x04\x1b" "\x64\x9a\x57\xa7", 65, 20, "\x65\x65\xcb\x30\xfb\x2c\x28\x54\x7c\xd0\x4c\x1d\x6a\x88\xf2\x7a" "\x6d\xe8\x55\x3d", 20 }, { GCRY_MD_BLAKE2S_224, "", "\xa8\x66\x86\x63\x35\x3a\xe0\x8f\x4e\x4b\x6b\x1e\xcb\x43\x19\xc8" "\x2b\x41\x3f\x5e\xe5\x43\x95\x9c\xa5\x9a\x73\x1b", 0, 28, "\x5a\x5a\xb5\x10\xc6\xd7\x9e\x76\x14\x8a\x9e\x29\xc8\xf1\xba\xab" "\x65\x11\x77\x89\x00\x89\x8a\x14\x9f\xb4\x53\x07", 28 }, { GCRY_MD_BLAKE2S_224, "\x9c\x9c\x38", "\x1a\x34\x9d\xc1\x51\xbd\x8b\xa2\xa7\xa6\x6b\xe4\x93\x98\x51\x88" "\x33\x49\x71\x02\x09\xb1\x20\x85\x8c\x4c\x67\xb8", 3, 28, "\x5a\x5a\xb5\x10\xc6\xd7\x9e\x76\x14\x8a\x9e\x29\xc8\xf1\xba\xab" "\x65\x11\x77\x89\x00\x89\x8a\x14\x9f\xb4\x53\x07", 28 }, { GCRY_MD_BLAKE2S_224, "\xab\xab\x56\x01\x58\x5a\xb3\x0d\xc1\xce\x8f\x5e\xee\x4d\x3b\x88" "\xc4\x4c\x11\x5e\x6f\xcd\x3d\x0a\x47\x52\x9a\xec\x86\x73\xfa\x6e" "\x68\xd6\x3f\x16\x55\x6b\xc1\x2d\xef\x1d\x0c\x29\x35\x5f\x94\xf3" "\x88\x7c\x04\x81\x86\x07\x8e\x95\x23\xb9\xdd\x97\x74\x0c\x80\x8c", "\x3a\x0e\xd5\x46\x95\x8c\xd6\xf9\x7c\x38\xd0\xe7\x1c\xfd\xd4\xc5" "\x67\x6d\x5c\xcc\x35\x06\xec\x87\x87\x09\x26\x39", 64, 28, "\x5a\x5a\xb5\x10\xc6\xd7\x9e\x76\x14\x8a\x9e\x29\xc8\xf1\xba\xab" "\x65\x11\x77\x89\x00\x89\x8a\x14\x9f\xb4\x53\x07", 28 }, { GCRY_MD_BLAKE2S_224, "\x8a\x8a\x14\x9e\xb2\x50\x02\x52\x54\xa6\xfa\xa0\x9a\x3a\xd4\x0e" "\xe3\xf2\xd5\xc7\x9d\x64\x02\x66\x68\xcf\x38\x08\x41\x49\x8a\xd3" "\x5e\x32\x90\xc2\x53\x15\x68\x7e\xe6\x65\x4b\xb0\xfc\xad\xaa\x58" "\x02\x5b\x5e\xb9\x18\xd1\xe9\xbb\xa5\x61\x07\x68\x70\xd9\x49\x22" "\x6b", "\x63\xd7\x98\xcc\x8e\xe3\x00\x45\x2f\xd8\x19\x83\x02\x94\x7f\xf1" "\xb3\x82\x73\xaa\x19\xae\x72\x8b\x1f\x64\xbe\x88", 65, 28, "\x5a\x5a\xb5\x10\xc6\xd7\x9e\x76\x14\x8a\x9e\x29\xc8\xf1\xba\xab" "\x65\x11\x77\x89\x00\x89\x8a\x14\x9f\xb4\x53\x07", 28 }, { GCRY_MD_BLAKE2S_256, "", "\x98\xf3\x21\xe5\x43\xb8\x07\x35\x27\x9c\x86\x1c\x36\x33\x9b\x43" "\x45\x50\xc6\x9d\x23\xc6\xc8\xff\x96\xbf\x4e\x03\x86\x10\x24\xfd", 0, 32, "\xd5\xd5\xab\x80\x2c\xad\xd9\x86\x60\xe7\x47\x2f\x77\xa6\x1d\xc4" "\xe2\xa6\x88\x2f\xb7\xe6\x9e\x85\x23\xa9\xcd\x76\x43\xb9\xfd\xb7", 32 }, { GCRY_MD_BLAKE2S_256, "\x9c\x9c\x38", "\x7b\x10\xa3\x67\xb8\x5d\x29\x9a\x91\x27\x37\x05\x9d\x05\x9d\x3d" "\xe6\x42\xa3\x19\x04\x57\x01\xb6\x25\x0b\xfd\x3c\x6c\xb9\x4f\x87", 3, 32, "\xd5\xd5\xab\x80\x2c\xad\xd9\x86\x60\xe7\x47\x2f\x77\xa6\x1d\xc4" "\xe2\xa6\x88\x2f\xb7\xe6\x9e\x85\x23\xa9\xcd\x76\x43\xb9\xfd\xb7", 32 }, { GCRY_MD_BLAKE2S_256, "\xab\xab\x56\x01\x58\x5a\xb3\x0d\xc1\xce\x8f\x5e\xee\x4d\x3b\x88" "\xc4\x4c\x11\x5e\x6f\xcd\x3d\x0a\x47\x52\x9a\xec\x86\x73\xfa\x6e" "\x68\xd6\x3f\x16\x55\x6b\xc1\x2d\xef\x1d\x0c\x29\x35\x5f\x94\xf3" "\x88\x7c\x04\x81\x86\x07\x8e\x95\x23\xb9\xdd\x97\x74\x0c\x80\x8c", "\xd7\x8b\x98\x28\x54\x4c\xc1\x62\x9e\xab\x7d\xfe\xb1\xfa\xdd\x2b" "\xed\x98\x1c\xe6\x5f\xef\xd8\x08\x42\x9a\x11\x1e\x97\x44\x92\xa3", 64, 32, "\xd5\xd5\xab\x80\x2c\xad\xd9\x86\x60\xe7\x47\x2f\x77\xa6\x1d\xc4" "\xe2\xa6\x88\x2f\xb7\xe6\x9e\x85\x23\xa9\xcd\x76\x43\xb9\xfd\xb7", 32 }, { GCRY_MD_BLAKE2S_256, "\x8a\x8a\x14\x9e\xb2\x50\x02\x52\x54\xa6\xfa\xa0\x9a\x3a\xd4\x0e" "\xe3\xf2\xd5\xc7\x9d\x64\x02\x66\x68\xcf\x38\x08\x41\x49\x8a\xd3" "\x5e\x32\x90\xc2\x53\x15\x68\x7e\xe6\x65\x4b\xb0\xfc\xad\xaa\x58" "\x02\x5b\x5e\xb9\x18\xd1\xe9\xbb\xa5\x61\x07\x68\x70\xd9\x49\x22" "\x6b", "\x1b\x9e\x26\x9a\x90\xf8\x73\x51\x73\xbc\x4f\x65\xce\x29\x2c\x61" "\x16\x65\xc7\xb0\x72\x07\xa8\x0b\xfb\x2e\xea\x12\x7d\x97\xcd\x06", 65, 32, "\xd5\xd5\xab\x80\x2c\xad\xd9\x86\x60\xe7\x47\x2f\x77\xa6\x1d\xc4" "\xe2\xa6\x88\x2f\xb7\xe6\x9e\x85\x23\xa9\xcd\x76\x43\xb9\xfd\xb7", 32 }, { GCRY_MD_BLAKE2S_256, "!", "\xbe\xc0\xc0\xe6\xcd\xe5\xb6\x7a\xcb\x73\xb8\x1f\x79\xa6\x7a\x40" "\x79\xae\x1c\x60\xda\xc9\xd2\x66\x1a\xf1\x8e\x9f\x8b\x50\xdf\xa5" }, { GCRY_MD_BLAKE2S_256, "?", "\xdc\x5a\xe7\x1b\xd4\x63\xa1\xf8\x4d\x73\x33\x44\x63\x6b\xa6\x87" "\xe6\xbd\xf4\xba\xed\xc3\xef\xc8\xb3\x86\x55\xbb\x08\x56\x3e\xdb" }, { GCRY_MD_BLAKE2S_224, "?", "\x2e\x34\x7d\x6b\xcc\x80\xbe\xc3\xf8\x61\x35\x6a\x88\x27\xcd\x84" "\x32\xd4\xd4\x05\xe0\x43\x20\x58\xc7\xb6\xda\xa3" }, { GCRY_MD_BLAKE2S_160, "?", "\xaa\x83\xe1\xcd\x8d\x4e\x9c\xb7\xf4\x6b\x43\xe1\xbc\x6f\x73\x3b" "\x0e\xfc\x29\xde" }, { GCRY_MD_BLAKE2S_128, "?", "\x70\x0b\x8a\x71\x1d\x34\x0a\xf0\x13\x93\x19\x93\x5e\xd7\x54\x9c" }, { 0 } }; gcry_error_t err; int i; if (verbose) fprintf (stderr, "Starting hash checks.\n"); for (i = 0; algos[i].md; i++) { if (gcry_md_test_algo (algos[i].md)) { show_md_not_available (algos[i].md); continue; } if (gcry_md_test_algo (algos[i].md) && in_fips_mode) { if (verbose) fprintf (stderr, " algorithm %d not available in fips mode\n", algos[i].md); continue; } if (verbose) fprintf (stderr, " checking %s [%i] for length %d\n", gcry_md_algo_name (algos[i].md), algos[i].md, (!strcmp (algos[i].data, "!") || !strcmp (algos[i].data, "?"))? 1000000 : (int)strlen(algos[i].data)); check_one_md (algos[i].md, algos[i].data, algos[i].datalen > 0 ? algos[i].datalen : strlen (algos[i].data), algos[i].expect, algos[i].expectlen, algos[i].key, algos[i].keylen); if (algos[i].key && algos[i].keylen) continue; check_one_md_multi (algos[i].md, algos[i].data, algos[i].datalen > 0 ? algos[i].datalen : strlen (algos[i].data), algos[i].expect); } /* Check the Whirlpool bug emulation. */ if (!gcry_md_test_algo (GCRY_MD_WHIRLPOOL) && !in_fips_mode) { static const char expect[] = "\x35\x28\xd6\x4c\x56\x2c\x55\x2e\x3b\x91\x93\x95\x7b\xdd\xcc\x6e" "\x6f\xb7\xbf\x76\x22\x9c\xc6\x23\xda\x3e\x09\x9b\x36\xe8\x6d\x76" "\x2f\x94\x3b\x0c\x63\xa0\xba\xa3\x4d\x66\x71\xe6\x5d\x26\x67\x28" "\x36\x1f\x0e\x1a\x40\xf0\xce\x83\x50\x90\x1f\xfa\x3f\xed\x6f\xfd"; gcry_md_hd_t hd; int algo = GCRY_MD_WHIRLPOOL; unsigned char *p; int mdlen; err = gcry_md_open (&hd, GCRY_MD_WHIRLPOOL, GCRY_MD_FLAG_BUGEMU1); if (err) { fail ("algo %d, gcry_md_open failed: %s\n", algo, gpg_strerror (err)); goto leave; } mdlen = gcry_md_get_algo_dlen (algo); if (mdlen < 1 || mdlen > 500) { fail ("algo %d, gcry_md_get_algo_dlen failed: %d\n", algo, mdlen); gcry_md_close (hd); goto leave; } /* Hash 62 byes in chunks. */ gcry_md_write (hd, "1234567890", 10); gcry_md_write (hd, "1234567890123456789012345678901234567890123456789012", 52); p = gcry_md_read (hd, algo); if (memcmp (p, expect, mdlen)) { printf ("computed: "); for (i = 0; i < mdlen; i++) printf ("%02x ", p[i] & 0xFF); printf ("\nexpected: "); for (i = 0; i < mdlen; i++) printf ("%02x ", expect[i] & 0xFF); printf ("\n"); fail ("algo %d, digest mismatch\n", algo); } gcry_md_close (hd); } leave: if (verbose) fprintf (stderr, "Completed hash checks.\n"); } static void check_one_hmac (int algo, const char *data, int datalen, const char *key, int keylen, const char *expect) { gcry_md_hd_t hd, hd2; unsigned char *p; int mdlen; int i; gcry_error_t err = 0; err = gcry_md_open (&hd, algo, GCRY_MD_FLAG_HMAC); if (err) { fail ("algo %d, gcry_md_open failed: %s\n", algo, gpg_strerror (err)); return; } mdlen = gcry_md_get_algo_dlen (algo); if (mdlen < 1 || mdlen > 500) { fail ("algo %d, gcry_md_get_algo_dlen failed: %d\n", algo, mdlen); return; } gcry_md_setkey( hd, key, keylen ); gcry_md_write (hd, data, datalen); err = gcry_md_copy (&hd2, hd); if (err) { fail ("algo %d, gcry_md_copy failed: %s\n", algo, gpg_strerror (err)); } gcry_md_close (hd); p = gcry_md_read (hd2, algo); if (!p) fail("algo %d, hmac gcry_md_read failed\n", algo); if (memcmp (p, expect, mdlen)) { printf ("computed: "); for (i = 0; i < mdlen; i++) printf ("%02x ", p[i] & 0xFF); printf ("\nexpected: "); for (i = 0; i < mdlen; i++) printf ("%02x ", expect[i] & 0xFF); printf ("\n"); fail ("algo %d, digest mismatch\n", algo); } gcry_md_close (hd2); } static void check_hmac (void) { static const struct algos { int md; const char *data; const char *key; const char *expect; } algos[] = { { GCRY_MD_MD5, "what do ya want for nothing?", "Jefe", "\x75\x0c\x78\x3e\x6a\xb0\xb5\x03\xea\xa8\x6e\x31\x0a\x5d\xb7\x38" }, { GCRY_MD_MD5, "Hi There", "\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b", "\x92\x94\x72\x7a\x36\x38\xbb\x1c\x13\xf4\x8e\xf8\x15\x8b\xfc\x9d" }, { GCRY_MD_MD5, "\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd" "\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd" "\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd" "\xdd\xdd\xdd\xdd\xdd", "\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA", "\x56\xbe\x34\x52\x1d\x14\x4c\x88\xdb\xb8\xc7\x33\xf0\xe8\xb3\xf6" }, { GCRY_MD_MD5, "\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd" "\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd" "\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd" "\xcd\xcd\xcd\xcd\xcd", "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19", "\x69\x7e\xaf\x0a\xca\x3a\x3a\xea\x3a\x75\x16\x47\x46\xff\xaa\x79" }, { GCRY_MD_MD5, "Test With Truncation", "\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c", "\x56\x46\x1e\xf2\x34\x2e\xdc\x00\xf9\xba\xb9\x95\x69\x0e\xfd\x4c" }, { GCRY_MD_MD5, "Test Using Larger Than Block-Size Key - Hash Key First", "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa", "\x6b\x1a\xb7\xfe\x4b\xd7\xbf\x8f\x0b\x62\xe6\xce\x61\xb9\xd0\xcd" }, { GCRY_MD_MD5, "Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data", "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa", "\x6f\x63\x0f\xad\x67\xcd\xa0\xee\x1f\xb1\xf5\x62\xdb\x3a\xa5\x3e", }, { GCRY_MD_SHA256, "what do ya want for nothing?", "Jefe", "\x5b\xdc\xc1\x46\xbf\x60\x75\x4e\x6a\x04\x24\x26\x08\x95\x75\xc7\x5a" "\x00\x3f\x08\x9d\x27\x39\x83\x9d\xec\x58\xb9\x64\xec\x38\x43" }, { GCRY_MD_SHA256, "Hi There", "\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b" "\x0b\x0b\x0b", "\xb0\x34\x4c\x61\xd8\xdb\x38\x53\x5c\xa8\xaf\xce\xaf\x0b\xf1\x2b\x88" "\x1d\xc2\x00\xc9\x83\x3d\xa7\x26\xe9\x37\x6c\x2e\x32\xcf\xf7" }, { GCRY_MD_SHA256, "\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd" "\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd" "\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd" "\xdd\xdd\xdd\xdd\xdd", "\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA" "\xAA\xAA\xAA\xAA", "\x77\x3e\xa9\x1e\x36\x80\x0e\x46\x85\x4d\xb8\xeb\xd0\x91\x81\xa7" "\x29\x59\x09\x8b\x3e\xf8\xc1\x22\xd9\x63\x55\x14\xce\xd5\x65\xfe" }, { GCRY_MD_SHA256, "\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd" "\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd" "\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd" "\xcd\xcd\xcd\xcd\xcd", "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19", "\x82\x55\x8a\x38\x9a\x44\x3c\x0e\xa4\xcc\x81\x98\x99\xf2\x08" "\x3a\x85\xf0\xfa\xa3\xe5\x78\xf8\x07\x7a\x2e\x3f\xf4\x67\x29\x66\x5b" }, { GCRY_MD_SHA256, "Test Using Larger Than Block-Size Key - Hash Key First", "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa", "\x60\xe4\x31\x59\x1e\xe0\xb6\x7f\x0d\x8a\x26\xaa\xcb\xf5\xb7\x7f" "\x8e\x0b\xc6\x21\x37\x28\xc5\x14\x05\x46\x04\x0f\x0e\xe3\x7f\x54" }, { GCRY_MD_SHA256, "This is a test using a larger than block-size key and a larger than block-size data. The key needs to be hashed before being used by the HMAC algorithm.", "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa", "\x9b\x09\xff\xa7\x1b\x94\x2f\xcb\x27\x63\x5f\xbc\xd5\xb0\xe9\x44" "\xbf\xdc\x63\x64\x4f\x07\x13\x93\x8a\x7f\x51\x53\x5c\x3a\x35\xe2" }, { GCRY_MD_SHA224, "what do ya want for nothing?", "Jefe", "\xa3\x0e\x01\x09\x8b\xc6\xdb\xbf\x45\x69\x0f\x3a\x7e\x9e\x6d\x0f" "\x8b\xbe\xa2\xa3\x9e\x61\x48\x00\x8f\xd0\x5e\x44" }, { GCRY_MD_SHA224, "Hi There", "\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b" "\x0b\x0b\x0b", "\x89\x6f\xb1\x12\x8a\xbb\xdf\x19\x68\x32\x10\x7c\xd4\x9d\xf3\x3f\x47" "\xb4\xb1\x16\x99\x12\xba\x4f\x53\x68\x4b\x22" }, { GCRY_MD_SHA224, "\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd" "\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd" "\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd" "\xdd\xdd\xdd\xdd\xdd", "\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA" "\xAA\xAA\xAA\xAA", "\x7f\xb3\xcb\x35\x88\xc6\xc1\xf6\xff\xa9\x69\x4d\x7d\x6a\xd2\x64" "\x93\x65\xb0\xc1\xf6\x5d\x69\xd1\xec\x83\x33\xea" }, { GCRY_MD_SHA224, "\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd" "\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd" "\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd" "\xcd\xcd\xcd\xcd\xcd", "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19", "\x6c\x11\x50\x68\x74\x01\x3c\xac\x6a\x2a\xbc\x1b\xb3\x82\x62" "\x7c\xec\x6a\x90\xd8\x6e\xfc\x01\x2d\xe7\xaf\xec\x5a" }, { GCRY_MD_SHA224, "Test Using Larger Than Block-Size Key - Hash Key First", "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa", "\x95\xe9\xa0\xdb\x96\x20\x95\xad\xae\xbe\x9b\x2d\x6f\x0d\xbc\xe2" "\xd4\x99\xf1\x12\xf2\xd2\xb7\x27\x3f\xa6\x87\x0e" }, { GCRY_MD_SHA224, "This is a test using a larger than block-size key and a larger than block-size data. The key needs to be hashed before being used by the HMAC algorithm.", "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa", "\x3a\x85\x41\x66\xac\x5d\x9f\x02\x3f\x54\xd5\x17\xd0\xb3\x9d\xbd" "\x94\x67\x70\xdb\x9c\x2b\x95\xc9\xf6\xf5\x65\xd1" }, { GCRY_MD_SHA384, "what do ya want for nothing?", "Jefe", "\xaf\x45\xd2\xe3\x76\x48\x40\x31\x61\x7f\x78\xd2\xb5\x8a\x6b\x1b" "\x9c\x7e\xf4\x64\xf5\xa0\x1b\x47\xe4\x2e\xc3\x73\x63\x22\x44\x5e" "\x8e\x22\x40\xca\x5e\x69\xe2\xc7\x8b\x32\x39\xec\xfa\xb2\x16\x49" }, { GCRY_MD_SHA384, "Hi There", "\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b" "\x0b\x0b\x0b", "\xaf\xd0\x39\x44\xd8\x48\x95\x62\x6b\x08\x25\xf4\xab\x46\x90\x7f\x15" "\xf9\xda\xdb\xe4\x10\x1e\xc6\x82\xaa\x03\x4c\x7c\xeb\xc5\x9c\xfa\xea" "\x9e\xa9\x07\x6e\xde\x7f\x4a\xf1\x52\xe8\xb2\xfa\x9c\xb6" }, { GCRY_MD_SHA384, "\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd" "\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd" "\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd" "\xdd\xdd\xdd\xdd\xdd", "\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA" "\xAA\xAA\xAA\xAA", "\x88\x06\x26\x08\xd3\xe6\xad\x8a\x0a\xa2\xac\xe0\x14\xc8\xa8\x6f" "\x0a\xa6\x35\xd9\x47\xac\x9f\xeb\xe8\x3e\xf4\xe5\x59\x66\x14\x4b" "\x2a\x5a\xb3\x9d\xc1\x38\x14\xb9\x4e\x3a\xb6\xe1\x01\xa3\x4f\x27" }, { GCRY_MD_SHA384, "\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd" "\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd" "\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd" "\xcd\xcd\xcd\xcd\xcd", "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19", "\x3e\x8a\x69\xb7\x78\x3c\x25\x85\x19\x33\xab\x62\x90\xaf\x6c\xa7" "\x7a\x99\x81\x48\x08\x50\x00\x9c\xc5\x57\x7c\x6e\x1f\x57\x3b\x4e" "\x68\x01\xdd\x23\xc4\xa7\xd6\x79\xcc\xf8\xa3\x86\xc6\x74\xcf\xfb" }, { GCRY_MD_SHA384, "Test Using Larger Than Block-Size Key - Hash Key First", "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa", "\x4e\xce\x08\x44\x85\x81\x3e\x90\x88\xd2\xc6\x3a\x04\x1b\xc5\xb4" "\x4f\x9e\xf1\x01\x2a\x2b\x58\x8f\x3c\xd1\x1f\x05\x03\x3a\xc4\xc6" "\x0c\x2e\xf6\xab\x40\x30\xfe\x82\x96\x24\x8d\xf1\x63\xf4\x49\x52" }, { GCRY_MD_SHA384, "This is a test using a larger than block-size key and a larger than block-size data. The key needs to be hashed before being used by the HMAC algorithm.", "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa", "\x66\x17\x17\x8e\x94\x1f\x02\x0d\x35\x1e\x2f\x25\x4e\x8f\xd3\x2c" "\x60\x24\x20\xfe\xb0\xb8\xfb\x9a\xdc\xce\xbb\x82\x46\x1e\x99\xc5" "\xa6\x78\xcc\x31\xe7\x99\x17\x6d\x38\x60\xe6\x11\x0c\x46\x52\x3e" }, { GCRY_MD_SHA512, "what do ya want for nothing?", "Jefe", "\x16\x4b\x7a\x7b\xfc\xf8\x19\xe2\xe3\x95\xfb\xe7\x3b\x56\xe0\xa3" "\x87\xbd\x64\x22\x2e\x83\x1f\xd6\x10\x27\x0c\xd7\xea\x25\x05\x54" "\x97\x58\xbf\x75\xc0\x5a\x99\x4a\x6d\x03\x4f\x65\xf8\xf0\xe6\xfd" "\xca\xea\xb1\xa3\x4d\x4a\x6b\x4b\x63\x6e\x07\x0a\x38\xbc\xe7\x37" }, { GCRY_MD_SHA512, "Hi There", "\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b" "\x0b\x0b\x0b", "\x87\xaa\x7c\xde\xa5\xef\x61\x9d\x4f\xf0\xb4\x24\x1a\x1d\x6c\xb0" "\x23\x79\xf4\xe2\xce\x4e\xc2\x78\x7a\xd0\xb3\x05\x45\xe1\x7c\xde" "\xda\xa8\x33\xb7\xd6\xb8\xa7\x02\x03\x8b\x27\x4e\xae\xa3\xf4\xe4" "\xbe\x9d\x91\x4e\xeb\x61\xf1\x70\x2e\x69\x6c\x20\x3a\x12\x68\x54" }, { GCRY_MD_SHA512, "\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd" "\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd" "\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd" "\xdd\xdd\xdd\xdd\xdd", "\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA" "\xAA\xAA\xAA\xAA", "\xfa\x73\xb0\x08\x9d\x56\xa2\x84\xef\xb0\xf0\x75\x6c\x89\x0b\xe9" "\xb1\xb5\xdb\xdd\x8e\xe8\x1a\x36\x55\xf8\x3e\x33\xb2\x27\x9d\x39" "\xbf\x3e\x84\x82\x79\xa7\x22\xc8\x06\xb4\x85\xa4\x7e\x67\xc8\x07" "\xb9\x46\xa3\x37\xbe\xe8\x94\x26\x74\x27\x88\x59\xe1\x32\x92\xfb" }, { GCRY_MD_SHA512, "\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd" "\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd" "\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd" "\xcd\xcd\xcd\xcd\xcd", "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19", "\xb0\xba\x46\x56\x37\x45\x8c\x69\x90\xe5\xa8\xc5\xf6\x1d\x4a\xf7" "\xe5\x76\xd9\x7f\xf9\x4b\x87\x2d\xe7\x6f\x80\x50\x36\x1e\xe3\xdb" "\xa9\x1c\xa5\xc1\x1a\xa2\x5e\xb4\xd6\x79\x27\x5c\xc5\x78\x80\x63" "\xa5\xf1\x97\x41\x12\x0c\x4f\x2d\xe2\xad\xeb\xeb\x10\xa2\x98\xdd" }, { GCRY_MD_SHA512, "Test Using Larger Than Block-Size Key - Hash Key First", "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa", "\x80\xb2\x42\x63\xc7\xc1\xa3\xeb\xb7\x14\x93\xc1\xdd\x7b\xe8\xb4" "\x9b\x46\xd1\xf4\x1b\x4a\xee\xc1\x12\x1b\x01\x37\x83\xf8\xf3\x52" "\x6b\x56\xd0\x37\xe0\x5f\x25\x98\xbd\x0f\xd2\x21\x5d\x6a\x1e\x52" "\x95\xe6\x4f\x73\xf6\x3f\x0a\xec\x8b\x91\x5a\x98\x5d\x78\x65\x98" }, { GCRY_MD_SHA512, "This is a test using a larger than block-size key and a larger than block-size data. The key needs to be hashed before being used by the HMAC algorithm.", "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa", "\xe3\x7b\x6a\x77\x5d\xc8\x7d\xba\xa4\xdf\xa9\xf9\x6e\x5e\x3f\xfd" "\xde\xbd\x71\xf8\x86\x72\x89\x86\x5d\xf5\xa3\x2d\x20\xcd\xc9\x44" "\xb6\x02\x2c\xac\x3c\x49\x82\xb1\x0d\x5e\xeb\x55\xc3\xe4\xde\x15" "\x13\x46\x76\xfb\x6d\xe0\x44\x60\x65\xc9\x74\x40\xfa\x8c\x6a\x58" }, { 0 }, }; int i; if (verbose) fprintf (stderr, "Starting hashed MAC checks.\n"); for (i = 0; algos[i].md; i++) { if (gcry_md_test_algo (algos[i].md)) { show_old_hmac_not_available (algos[i].md); continue; } if (gcry_md_test_algo (algos[i].md) && in_fips_mode) { if (verbose) fprintf (stderr, " algorithm %d not available in fips mode\n", algos[i].md); continue; } if (verbose) fprintf (stderr, " checking %s [%i] for %d byte key and %d byte data\n", gcry_md_algo_name (algos[i].md), algos[i].md, (int)strlen(algos[i].key), (int)strlen(algos[i].data)); check_one_hmac (algos[i].md, algos[i].data, strlen (algos[i].data), algos[i].key, strlen(algos[i].key), algos[i].expect); } if (verbose) fprintf (stderr, "Completed hashed MAC checks.\n"); } static void check_one_mac (int algo, const char *data, int datalen, const char *key, int keylen, const char *iv, int ivlen, const char *expect, int test_buffering) { gcry_mac_hd_t hd; unsigned char *p; unsigned int maclen; size_t macoutlen; int i; gcry_error_t err = 0; if (test_buffering) { if ((*data == '!' && !data[1]) || (*data == '?' && !data[1])) { return; /* Skip. */ } } err = gcry_mac_open (&hd, algo, 0, NULL); if (err) { fail ("algo %d, gcry_mac_open failed: %s\n", algo, gpg_strerror (err)); return; } i = gcry_mac_get_algo (hd); if (i != algo) { fail ("algo %d, gcry_mac_get_algo failed: %d\n", algo, i); } maclen = gcry_mac_get_algo_maclen (algo); if (maclen < 1 || maclen > 500) { fail ("algo %d, gcry_mac_get_algo_maclen failed: %d\n", algo, maclen); return; } p = malloc(maclen); if (!p) { fail ("algo %d, could not malloc %d bytes\n", algo, maclen); return; } err = gcry_mac_setkey (hd, key, keylen); if (err) fail("algo %d, mac gcry_mac_setkey failed: %s\n", algo, gpg_strerror (err)); if (err) goto out; if (ivlen && iv) { err = gcry_mac_setiv (hd, iv, ivlen); if (err) fail("algo %d, mac gcry_mac_ivkey failed: %s\n", algo, gpg_strerror (err)); if (err) goto out; } if (test_buffering) { for (i = 0; i < datalen; i++) { err = gcry_mac_write (hd, &data[i], 1); if (err) fail("algo %d, mac gcry_mac_write [buf-offset: %d] failed: %s\n", algo, i, gpg_strerror (err)); if (err) goto out; } } else { if ((*data == '!' && !data[1]) || /* hash one million times a "a" */ (*data == '?' && !data[1])) /* hash million byte data-set with byte pattern 0x00,0x01,0x02,... */ { char aaa[1000]; size_t left = 1000 * 1000; size_t startlen = 1; size_t piecelen = startlen; if (*data == '!') memset (aaa, 'a', 1000); /* Write in chuck with all sizes 1 to 1000 (500500 bytes) */ for (i = 1; i <= 1000 && left > 0; i++) { piecelen = i; if (piecelen > sizeof(aaa)) piecelen = sizeof(aaa); if (piecelen > left) piecelen = left; if (*data == '?') fillbuf_count(aaa, piecelen, 1000 * 1000 - left); gcry_mac_write (hd, aaa, piecelen); left -= piecelen; } /* Write in odd size chunks so that we test the buffering. */ while (left > 0) { if (piecelen > sizeof(aaa)) piecelen = sizeof(aaa); if (piecelen > left) piecelen = left; if (*data == '?') fillbuf_count(aaa, piecelen, 1000 * 1000 - left); gcry_mac_write (hd, aaa, piecelen); left -= piecelen; if (piecelen == sizeof(aaa)) piecelen = ++startlen; else piecelen = piecelen * 2 - ((piecelen != startlen) ? startlen : 0); } } else { err = gcry_mac_write (hd, data, datalen); } if (err) fail("algo %d, mac gcry_mac_write failed: %s\n", algo, gpg_strerror (err)); if (err) goto out; } err = gcry_mac_verify (hd, expect, maclen); if (err) fail("algo %d, mac gcry_mac_verify failed: %s\n", algo, gpg_strerror (err)); macoutlen = maclen; err = gcry_mac_read (hd, p, &macoutlen); if (err) fail("algo %d, mac gcry_mac_read failed: %s\n", algo, gpg_strerror (err)); if (err) goto out; if (memcmp (p, expect, maclen)) { printf ("computed: "); for (i = 0; i < maclen; i++) printf ("%02x ", p[i] & 0xFF); printf ("\nexpected: "); for (i = 0; i < maclen; i++) printf ("%02x ", expect[i] & 0xFF); printf ("\n"); fail ("algo %d, digest mismatch\n", algo); } if (err) goto out; out: free (p); gcry_mac_close (hd); } static void check_mac (void) { static const struct algos { int algo; const char *data; const char *key; const char *expect; const char *iv; unsigned int dlen; unsigned int klen; } algos[] = { { GCRY_MAC_HMAC_MD5, "what do ya want for nothing?", "Jefe", "\x75\x0c\x78\x3e\x6a\xb0\xb5\x03\xea\xa8\x6e\x31\x0a\x5d\xb7\x38" }, { GCRY_MAC_HMAC_MD5, "Hi There", "\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b", "\x92\x94\x72\x7a\x36\x38\xbb\x1c\x13\xf4\x8e\xf8\x15\x8b\xfc\x9d" }, { GCRY_MAC_HMAC_MD5, "\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd" "\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd" "\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd" "\xdd\xdd\xdd\xdd\xdd", "\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA", "\x56\xbe\x34\x52\x1d\x14\x4c\x88\xdb\xb8\xc7\x33\xf0\xe8\xb3\xf6" }, { GCRY_MAC_HMAC_MD5, "\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd" "\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd" "\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd" "\xcd\xcd\xcd\xcd\xcd", "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19", "\x69\x7e\xaf\x0a\xca\x3a\x3a\xea\x3a\x75\x16\x47\x46\xff\xaa\x79" }, { GCRY_MAC_HMAC_MD5, "Test With Truncation", "\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c", "\x56\x46\x1e\xf2\x34\x2e\xdc\x00\xf9\xba\xb9\x95\x69\x0e\xfd\x4c" }, { GCRY_MAC_HMAC_MD5, "Test Using Larger Than Block-Size Key - Hash Key First", "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa", "\x6b\x1a\xb7\xfe\x4b\xd7\xbf\x8f\x0b\x62\xe6\xce\x61\xb9\xd0\xcd" }, { GCRY_MAC_HMAC_MD5, "Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data", "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa", "\x6f\x63\x0f\xad\x67\xcd\xa0\xee\x1f\xb1\xf5\x62\xdb\x3a\xa5\x3e", }, { GCRY_MAC_HMAC_MD5, "?", "????????????????", "\x7e\x28\xf8\x8e\xf4\x6c\x48\x30\xa2\x0c\xe3\xe1\x42\xd4\xb5\x6b" }, { GCRY_MAC_HMAC_SHA256, "what do ya want for nothing?", "Jefe", "\x5b\xdc\xc1\x46\xbf\x60\x75\x4e\x6a\x04\x24\x26\x08\x95\x75\xc7\x5a" "\x00\x3f\x08\x9d\x27\x39\x83\x9d\xec\x58\xb9\x64\xec\x38\x43" }, { GCRY_MAC_HMAC_SHA256, "Hi There", "\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b" "\x0b\x0b\x0b", "\xb0\x34\x4c\x61\xd8\xdb\x38\x53\x5c\xa8\xaf\xce\xaf\x0b\xf1\x2b\x88" "\x1d\xc2\x00\xc9\x83\x3d\xa7\x26\xe9\x37\x6c\x2e\x32\xcf\xf7" }, { GCRY_MAC_HMAC_SHA256, "\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd" "\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd" "\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd" "\xdd\xdd\xdd\xdd\xdd", "\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA" "\xAA\xAA\xAA\xAA", "\x77\x3e\xa9\x1e\x36\x80\x0e\x46\x85\x4d\xb8\xeb\xd0\x91\x81\xa7" "\x29\x59\x09\x8b\x3e\xf8\xc1\x22\xd9\x63\x55\x14\xce\xd5\x65\xfe" }, { GCRY_MAC_HMAC_SHA256, "\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd" "\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd" "\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd" "\xcd\xcd\xcd\xcd\xcd", "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19", "\x82\x55\x8a\x38\x9a\x44\x3c\x0e\xa4\xcc\x81\x98\x99\xf2\x08" "\x3a\x85\xf0\xfa\xa3\xe5\x78\xf8\x07\x7a\x2e\x3f\xf4\x67\x29\x66\x5b" }, { GCRY_MAC_HMAC_SHA256, "Test Using Larger Than Block-Size Key - Hash Key First", "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa", "\x60\xe4\x31\x59\x1e\xe0\xb6\x7f\x0d\x8a\x26\xaa\xcb\xf5\xb7\x7f" "\x8e\x0b\xc6\x21\x37\x28\xc5\x14\x05\x46\x04\x0f\x0e\xe3\x7f\x54" }, { GCRY_MAC_HMAC_SHA256, "This is a test using a larger than block-size key and a larger than block-size data. The key needs to be hashed before being used by the HMAC algorithm.", "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa", "\x9b\x09\xff\xa7\x1b\x94\x2f\xcb\x27\x63\x5f\xbc\xd5\xb0\xe9\x44" "\xbf\xdc\x63\x64\x4f\x07\x13\x93\x8a\x7f\x51\x53\x5c\x3a\x35\xe2" }, { GCRY_MAC_HMAC_SHA256, "?", "????????????????", "\x1c\x0e\x57\xad\x4a\x02\xd2\x30\xce\x7e\xf8\x08\x23\x25\x71\x5e" "\x16\x9b\x30\xca\xc3\xf4\x99\xc5\x1d\x4c\x25\x32\xa9\xf2\x15\x28" }, { GCRY_MAC_HMAC_SHA224, "what do ya want for nothing?", "Jefe", "\xa3\x0e\x01\x09\x8b\xc6\xdb\xbf\x45\x69\x0f\x3a\x7e\x9e\x6d\x0f" "\x8b\xbe\xa2\xa3\x9e\x61\x48\x00\x8f\xd0\x5e\x44" }, { GCRY_MAC_HMAC_SHA224, "Hi There", "\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b" "\x0b\x0b\x0b", "\x89\x6f\xb1\x12\x8a\xbb\xdf\x19\x68\x32\x10\x7c\xd4\x9d\xf3\x3f\x47" "\xb4\xb1\x16\x99\x12\xba\x4f\x53\x68\x4b\x22" }, { GCRY_MAC_HMAC_SHA224, "\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd" "\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd" "\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd" "\xdd\xdd\xdd\xdd\xdd", "\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA" "\xAA\xAA\xAA\xAA", "\x7f\xb3\xcb\x35\x88\xc6\xc1\xf6\xff\xa9\x69\x4d\x7d\x6a\xd2\x64" "\x93\x65\xb0\xc1\xf6\x5d\x69\xd1\xec\x83\x33\xea" }, { GCRY_MAC_HMAC_SHA224, "\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd" "\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd" "\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd" "\xcd\xcd\xcd\xcd\xcd", "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19", "\x6c\x11\x50\x68\x74\x01\x3c\xac\x6a\x2a\xbc\x1b\xb3\x82\x62" "\x7c\xec\x6a\x90\xd8\x6e\xfc\x01\x2d\xe7\xaf\xec\x5a" }, { GCRY_MAC_HMAC_SHA224, "Test Using Larger Than Block-Size Key - Hash Key First", "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa", "\x95\xe9\xa0\xdb\x96\x20\x95\xad\xae\xbe\x9b\x2d\x6f\x0d\xbc\xe2" "\xd4\x99\xf1\x12\xf2\xd2\xb7\x27\x3f\xa6\x87\x0e" }, { GCRY_MAC_HMAC_SHA224, "This is a test using a larger than block-size key and a larger than block-size data. The key needs to be hashed before being used by the HMAC algorithm.", "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa", "\x3a\x85\x41\x66\xac\x5d\x9f\x02\x3f\x54\xd5\x17\xd0\xb3\x9d\xbd" "\x94\x67\x70\xdb\x9c\x2b\x95\xc9\xf6\xf5\x65\xd1" }, { GCRY_MAC_HMAC_SHA224, "?", "????????????????", "\xc1\x88\xaf\xcf\xce\x51\xa2\x14\x3d\xc1\xaf\x93\xcc\x2b\xe9\x4d" "\x39\x55\x90\x4c\x46\x70\xfc\xc2\x04\xcf\xab\xfa" }, { GCRY_MAC_HMAC_SHA384, "what do ya want for nothing?", "Jefe", "\xaf\x45\xd2\xe3\x76\x48\x40\x31\x61\x7f\x78\xd2\xb5\x8a\x6b\x1b" "\x9c\x7e\xf4\x64\xf5\xa0\x1b\x47\xe4\x2e\xc3\x73\x63\x22\x44\x5e" "\x8e\x22\x40\xca\x5e\x69\xe2\xc7\x8b\x32\x39\xec\xfa\xb2\x16\x49" }, { GCRY_MAC_HMAC_SHA384, "Hi There", "\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b" "\x0b\x0b\x0b", "\xaf\xd0\x39\x44\xd8\x48\x95\x62\x6b\x08\x25\xf4\xab\x46\x90\x7f\x15" "\xf9\xda\xdb\xe4\x10\x1e\xc6\x82\xaa\x03\x4c\x7c\xeb\xc5\x9c\xfa\xea" "\x9e\xa9\x07\x6e\xde\x7f\x4a\xf1\x52\xe8\xb2\xfa\x9c\xb6" }, { GCRY_MAC_HMAC_SHA384, "\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd" "\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd" "\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd" "\xdd\xdd\xdd\xdd\xdd", "\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA" "\xAA\xAA\xAA\xAA", "\x88\x06\x26\x08\xd3\xe6\xad\x8a\x0a\xa2\xac\xe0\x14\xc8\xa8\x6f" "\x0a\xa6\x35\xd9\x47\xac\x9f\xeb\xe8\x3e\xf4\xe5\x59\x66\x14\x4b" "\x2a\x5a\xb3\x9d\xc1\x38\x14\xb9\x4e\x3a\xb6\xe1\x01\xa3\x4f\x27" }, { GCRY_MAC_HMAC_SHA384, "\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd" "\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd" "\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd" "\xcd\xcd\xcd\xcd\xcd", "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19", "\x3e\x8a\x69\xb7\x78\x3c\x25\x85\x19\x33\xab\x62\x90\xaf\x6c\xa7" "\x7a\x99\x81\x48\x08\x50\x00\x9c\xc5\x57\x7c\x6e\x1f\x57\x3b\x4e" "\x68\x01\xdd\x23\xc4\xa7\xd6\x79\xcc\xf8\xa3\x86\xc6\x74\xcf\xfb" }, { GCRY_MAC_HMAC_SHA384, "Test Using Larger Than Block-Size Key - Hash Key First", "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa", "\x4e\xce\x08\x44\x85\x81\x3e\x90\x88\xd2\xc6\x3a\x04\x1b\xc5\xb4" "\x4f\x9e\xf1\x01\x2a\x2b\x58\x8f\x3c\xd1\x1f\x05\x03\x3a\xc4\xc6" "\x0c\x2e\xf6\xab\x40\x30\xfe\x82\x96\x24\x8d\xf1\x63\xf4\x49\x52" }, { GCRY_MAC_HMAC_SHA384, "This is a test using a larger than block-size key and a larger than block-size data. The key needs to be hashed before being used by the HMAC algorithm.", "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa", "\x66\x17\x17\x8e\x94\x1f\x02\x0d\x35\x1e\x2f\x25\x4e\x8f\xd3\x2c" "\x60\x24\x20\xfe\xb0\xb8\xfb\x9a\xdc\xce\xbb\x82\x46\x1e\x99\xc5" "\xa6\x78\xcc\x31\xe7\x99\x17\x6d\x38\x60\xe6\x11\x0c\x46\x52\x3e" }, { GCRY_MAC_HMAC_SHA384, "?", "????????????????", "\xe7\x96\x29\xa3\x40\x5f\x1e\x6e\x92\xa5\xdb\xa5\xc6\xe9\x60\xa8" "\xf5\xd1\x6d\xcb\x10\xec\x30\x2f\x6b\x9c\x37\xe0\xea\xf1\x53\x28" "\x08\x01\x9b\xe3\x4a\x43\xc6\xc2\x2b\x0c\xd9\x43\x64\x35\x25\x78" }, { GCRY_MAC_HMAC_SHA512, "what do ya want for nothing?", "Jefe", "\x16\x4b\x7a\x7b\xfc\xf8\x19\xe2\xe3\x95\xfb\xe7\x3b\x56\xe0\xa3" "\x87\xbd\x64\x22\x2e\x83\x1f\xd6\x10\x27\x0c\xd7\xea\x25\x05\x54" "\x97\x58\xbf\x75\xc0\x5a\x99\x4a\x6d\x03\x4f\x65\xf8\xf0\xe6\xfd" "\xca\xea\xb1\xa3\x4d\x4a\x6b\x4b\x63\x6e\x07\x0a\x38\xbc\xe7\x37" }, { GCRY_MAC_HMAC_SHA512, "Hi There", "\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b" "\x0b\x0b\x0b", "\x87\xaa\x7c\xde\xa5\xef\x61\x9d\x4f\xf0\xb4\x24\x1a\x1d\x6c\xb0" "\x23\x79\xf4\xe2\xce\x4e\xc2\x78\x7a\xd0\xb3\x05\x45\xe1\x7c\xde" "\xda\xa8\x33\xb7\xd6\xb8\xa7\x02\x03\x8b\x27\x4e\xae\xa3\xf4\xe4" "\xbe\x9d\x91\x4e\xeb\x61\xf1\x70\x2e\x69\x6c\x20\x3a\x12\x68\x54" }, { GCRY_MAC_HMAC_SHA512, "\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd" "\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd" "\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd" "\xdd\xdd\xdd\xdd\xdd", "\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA" "\xAA\xAA\xAA\xAA", "\xfa\x73\xb0\x08\x9d\x56\xa2\x84\xef\xb0\xf0\x75\x6c\x89\x0b\xe9" "\xb1\xb5\xdb\xdd\x8e\xe8\x1a\x36\x55\xf8\x3e\x33\xb2\x27\x9d\x39" "\xbf\x3e\x84\x82\x79\xa7\x22\xc8\x06\xb4\x85\xa4\x7e\x67\xc8\x07" "\xb9\x46\xa3\x37\xbe\xe8\x94\x26\x74\x27\x88\x59\xe1\x32\x92\xfb" }, { GCRY_MAC_HMAC_SHA512, "\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd" "\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd" "\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd" "\xcd\xcd\xcd\xcd\xcd", "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19", "\xb0\xba\x46\x56\x37\x45\x8c\x69\x90\xe5\xa8\xc5\xf6\x1d\x4a\xf7" "\xe5\x76\xd9\x7f\xf9\x4b\x87\x2d\xe7\x6f\x80\x50\x36\x1e\xe3\xdb" "\xa9\x1c\xa5\xc1\x1a\xa2\x5e\xb4\xd6\x79\x27\x5c\xc5\x78\x80\x63" "\xa5\xf1\x97\x41\x12\x0c\x4f\x2d\xe2\xad\xeb\xeb\x10\xa2\x98\xdd" }, { GCRY_MAC_HMAC_SHA512, "Test Using Larger Than Block-Size Key - Hash Key First", "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa", "\x80\xb2\x42\x63\xc7\xc1\xa3\xeb\xb7\x14\x93\xc1\xdd\x7b\xe8\xb4" "\x9b\x46\xd1\xf4\x1b\x4a\xee\xc1\x12\x1b\x01\x37\x83\xf8\xf3\x52" "\x6b\x56\xd0\x37\xe0\x5f\x25\x98\xbd\x0f\xd2\x21\x5d\x6a\x1e\x52" "\x95\xe6\x4f\x73\xf6\x3f\x0a\xec\x8b\x91\x5a\x98\x5d\x78\x65\x98" }, { GCRY_MAC_HMAC_SHA512, "This is a test using a larger than block-size key and a larger than block-size data. The key needs to be hashed before being used by the HMAC algorithm.", "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa", "\xe3\x7b\x6a\x77\x5d\xc8\x7d\xba\xa4\xdf\xa9\xf9\x6e\x5e\x3f\xfd" "\xde\xbd\x71\xf8\x86\x72\x89\x86\x5d\xf5\xa3\x2d\x20\xcd\xc9\x44" "\xb6\x02\x2c\xac\x3c\x49\x82\xb1\x0d\x5e\xeb\x55\xc3\xe4\xde\x15" "\x13\x46\x76\xfb\x6d\xe0\x44\x60\x65\xc9\x74\x40\xfa\x8c\x6a\x58" }, { GCRY_MAC_HMAC_SHA512, "?", "????????????????", "\xd4\x43\x61\xfa\x3d\x3d\x57\xd6\xac\xc3\x9f\x1c\x3d\xd9\x26\x84" "\x1f\xfc\x4d\xf2\xbf\x78\x87\x72\x5e\x6c\x3e\x00\x6d\x39\x5f\xfa" "\xd7\x3a\xf7\x83\xb7\xb5\x61\xbd\xfb\x33\xe0\x03\x97\xa7\x72\x79" "\x66\x66\xbf\xbd\x44\xfa\x04\x01\x1b\xc1\x48\x1d\x9e\xde\x5b\x8e" }, /* HMAC-SHA3 test vectors from * http://wolfgang-ehrhardt.de/hmac-sha3-testvectors.html */ { GCRY_MAC_HMAC_SHA3_224, "Hi There", "\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b" "\x0b\x0b\x0b", "\x3b\x16\x54\x6b\xbc\x7b\xe2\x70\x6a\x03\x1d\xca\xfd\x56\x37\x3d" "\x98\x84\x36\x76\x41\xd8\xc5\x9a\xf3\xc8\x60\xf7" }, { GCRY_MAC_HMAC_SHA3_256, "Hi There", "\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b" "\x0b\x0b\x0b", "\xba\x85\x19\x23\x10\xdf\xfa\x96\xe2\xa3\xa4\x0e\x69\x77\x43\x51" "\x14\x0b\xb7\x18\x5e\x12\x02\xcd\xcc\x91\x75\x89\xf9\x5e\x16\xbb" }, { GCRY_MAC_HMAC_SHA3_512, "Hi There", "\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b" "\x0b\x0b\x0b", "\xeb\x3f\xbd\x4b\x2e\xaa\xb8\xf5\xc5\x04\xbd\x3a\x41\x46\x5a\xac" "\xec\x15\x77\x0a\x7c\xab\xac\x53\x1e\x48\x2f\x86\x0b\x5e\xc7\xba" "\x47\xcc\xb2\xc6\xf2\xaf\xce\x8f\x88\xd2\x2b\x6d\xc6\x13\x80\xf2" "\x3a\x66\x8f\xd3\x88\x8b\xb8\x05\x37\xc0\xa0\xb8\x64\x07\x68\x9e" }, { GCRY_MAC_HMAC_SHA3_224, "what do ya want for nothing?", "Jefe", "\x7f\xdb\x8d\xd8\x8b\xd2\xf6\x0d\x1b\x79\x86\x34\xad\x38\x68\x11" "\xc2\xcf\xc8\x5b\xfa\xf5\xd5\x2b\xba\xce\x5e\x66" }, { GCRY_MAC_HMAC_SHA3_256, "what do ya want for nothing?", "Jefe", "\xc7\xd4\x07\x2e\x78\x88\x77\xae\x35\x96\xbb\xb0\xda\x73\xb8\x87" "\xc9\x17\x1f\x93\x09\x5b\x29\x4a\xe8\x57\xfb\xe2\x64\x5e\x1b\xa5" }, { GCRY_MAC_HMAC_SHA3_384, "what do ya want for nothing?", "Jefe", "\xf1\x10\x1f\x8c\xbf\x97\x66\xfd\x67\x64\xd2\xed\x61\x90\x3f\x21" "\xca\x9b\x18\xf5\x7c\xf3\xe1\xa2\x3c\xa1\x35\x08\xa9\x32\x43\xce" "\x48\xc0\x45\xdc\x00\x7f\x26\xa2\x1b\x3f\x5e\x0e\x9d\xf4\xc2\x0a" }, { GCRY_MAC_HMAC_SHA3_512, "what do ya want for nothing?", "Jefe", "\x5a\x4b\xfe\xab\x61\x66\x42\x7c\x7a\x36\x47\xb7\x47\x29\x2b\x83" "\x84\x53\x7c\xdb\x89\xaf\xb3\xbf\x56\x65\xe4\xc5\xe7\x09\x35\x0b" "\x28\x7b\xae\xc9\x21\xfd\x7c\xa0\xee\x7a\x0c\x31\xd0\x22\xa9\x5e" "\x1f\xc9\x2b\xa9\xd7\x7d\xf8\x83\x96\x02\x75\xbe\xb4\xe6\x20\x24" }, { GCRY_MAC_HMAC_SHA3_224, "Test Using Larger Than Block-Size Key - Hash Key First", "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa", "\xb9\x6d\x73\x0c\x14\x8c\x2d\xaa\xd8\x64\x9d\x83\xde\xfa\xa3\x71" "\x97\x38\xd3\x47\x75\x39\x7b\x75\x71\xc3\x85\x15" }, { GCRY_MAC_HMAC_SHA3_256, "Test Using Larger Than Block-Size Key - Hash Key First", "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa", "\xa6\x07\x2f\x86\xde\x52\xb3\x8b\xb3\x49\xfe\x84\xcd\x6d\x97\xfb" "\x6a\x37\xc4\xc0\xf6\x2a\xae\x93\x98\x11\x93\xa7\x22\x9d\x34\x67" }, { GCRY_MAC_HMAC_SHA3_384, "Test Using Larger Than Block-Size Key - Hash Key First", "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa", "\x71\x3d\xff\x03\x02\xc8\x50\x86\xec\x5a\xd0\x76\x8d\xd6\x5a\x13" "\xdd\xd7\x90\x68\xd8\xd4\xc6\x21\x2b\x71\x2e\x41\x64\x94\x49\x11" "\x14\x80\x23\x00\x44\x18\x5a\x99\x10\x3e\xd8\x20\x04\xdd\xbf\xcc" }, { GCRY_MAC_HMAC_SHA3_512, "Test Using Larger Than Block-Size Key - Hash Key First", "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa", "\xb1\x48\x35\xc8\x19\xa2\x90\xef\xb0\x10\xac\xe6\xd8\x56\x8d\xc6" "\xb8\x4d\xe6\x0b\xc4\x9b\x00\x4c\x3b\x13\xed\xa7\x63\x58\x94\x51" "\xe5\xdd\x74\x29\x28\x84\xd1\xbd\xce\x64\xe6\xb9\x19\xdd\x61\xdc" "\x9c\x56\xa2\x82\xa8\x1c\x0b\xd1\x4f\x1f\x36\x5b\x49\xb8\x3a\x5b" }, { GCRY_MAC_HMAC_SHA3_224, "This is a test using a larger than block-size key and a larger " "than block-size data. The key needs to be hashed before being " "used by the HMAC algorithm.", "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa", "\xc7\x9c\x9b\x09\x34\x24\xe5\x88\xa9\x87\x8b\xbc\xb0\x89\xe0\x18" "\x27\x00\x96\xe9\xb4\xb1\xa9\xe8\x22\x0c\x86\x6a" }, { GCRY_MAC_HMAC_SHA3_256, "This is a test using a larger than block-size key and a larger " "than block-size data. The key needs to be hashed before being " "used by the HMAC algorithm.", "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa", "\xe6\xa3\x6d\x9b\x91\x5f\x86\xa0\x93\xca\xc7\xd1\x10\xe9\xe0\x4c" "\xf1\xd6\x10\x0d\x30\x47\x55\x09\xc2\x47\x5f\x57\x1b\x75\x8b\x5a" }, { GCRY_MAC_HMAC_SHA3_384, "This is a test using a larger than block-size key and a larger " "than block-size data. The key needs to be hashed before being " "used by the HMAC algorithm.", "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa", "\xca\xd1\x8a\x8f\xf6\xc4\xcc\x3a\xd4\x87\xb9\x5f\x97\x69\xe9\xb6" "\x1c\x06\x2a\xef\xd6\x95\x25\x69\xe6\xe6\x42\x18\x97\x05\x4c\xfc" "\x70\xb5\xfd\xc6\x60\x5c\x18\x45\x71\x12\xfc\x6a\xaa\xd4\x55\x85" }, { GCRY_MAC_HMAC_SHA3_512, "This is a test using a larger than block-size key and a larger " "than block-size data. The key needs to be hashed before being " "used by the HMAC algorithm.", "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa", "\xdc\x03\x0e\xe7\x88\x70\x34\xf3\x2c\xf4\x02\xdf\x34\x62\x2f\x31" "\x1f\x3e\x6c\xf0\x48\x60\xc6\xbb\xd7\xfa\x48\x86\x74\x78\x2b\x46" "\x59\xfd\xbd\xf3\xfd\x87\x78\x52\x88\x5c\xfe\x6e\x22\x18\x5f\xe7" "\xb2\xee\x95\x20\x43\x62\x9b\xc9\xd5\xf3\x29\x8a\x41\xd0\x2c\x66" }, { GCRY_MAC_HMAC_SHA3_224, "?", "????????????????", "\x80\x2b\x3c\x84\xfe\x3e\x01\x22\x14\xf8\xba\x74\x79\xfd\xb5\x02" "\xea\x0c\x06\xa4\x7e\x01\xe3\x2c\xc7\x24\x89\xc3" }, { GCRY_MAC_HMAC_SHA3_256, "?", "????????????????", "\x6c\x7c\x96\x5b\x19\xba\xcd\x61\x69\x8a\x2c\x7a\x2b\x96\xa1\xc3" "\x33\xa0\x3c\x5d\x54\x87\x37\x60\xc8\x2f\xa2\xa6\x12\x38\x8d\x1b" }, { GCRY_MAC_HMAC_SHA3_384, "?", "????????????????", "\xc0\x20\xd0\x9b\xa7\xb9\xd5\xb8\xa6\xa4\xba\x20\x55\xd9\x0b\x35" "\x8b\xe0\xb7\xec\x1e\x9f\xe6\xb9\xbd\xd5\xe9\x9b\xfc\x0a\x11\x3a" "\x15\x41\xed\xfd\xef\x30\x8d\x03\xb8\xca\x3a\xa8\xc7\x2d\x89\x32" }, { GCRY_MAC_HMAC_SHA3_512, "?", "????????????????", "\xb4\xef\x24\xd2\x07\xa7\x01\xb3\xe1\x81\x11\x22\x93\x83\x64\xe0" "\x5e\xad\x03\xb7\x43\x4f\x87\xa1\x14\x8e\x17\x8f\x2a\x97\x7d\xe8" "\xbd\xb0\x37\x3b\x67\xb9\x97\x36\xa5\x82\x9b\xdc\x0d\xe4\x5a\x8c" "\x5e\xda\xb5\xca\xea\xa9\xb4\x6e\xba\xca\x25\xc8\xbf\xa1\x0e\xb0" }, { GCRY_MAC_HMAC_STRIBOG256, "\x01\x26\xbd\xb8\x78\x00\xaf\x21\x43\x41\x45\x65\x63\x78\x01\x00", "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f", "\xa1\xaa\x5f\x7d\xe4\x02\xd7\xb3\xd3\x23\xf2\x99\x1c\x8d\x45\x34" "\x01\x31\x37\x01\x0a\x83\x75\x4f\xd0\xaf\x6d\x7c\xd4\x92\x2e\xd9", NULL, 16, 32 }, { GCRY_MAC_HMAC_STRIBOG512, "\x01\x26\xbd\xb8\x78\x00\xaf\x21\x43\x41\x45\x65\x63\x78\x01\x00", "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f", "\xa5\x9b\xab\x22\xec\xae\x19\xc6\x5f\xbd\xe6\xe5\xf4\xe9\xf5\xd8" "\x54\x9d\x31\xf0\x37\xf9\xdf\x9b\x90\x55\x00\xe1\x71\x92\x3a\x77" "\x3d\x5f\x15\x30\xf2\xed\x7e\x96\x4c\xb2\xee\xdc\x29\xe9\xad\x2f" "\x3a\xfe\x93\xb2\x81\x4f\x79\xf5\x00\x0f\xfc\x03\x66\xc2\x51\xe6", NULL, 16, 32 }, /* CMAC AES and DES test vectors from http://web.archive.org/web/20130930212819/http://csrc.nist.gov/publica\ tions/nistpubs/800-38B/Updated_CMAC_Examples.pdf */ { GCRY_MAC_CMAC_AES, "", "\x2b\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c", "\xbb\x1d\x69\x29\xe9\x59\x37\x28\x7f\xa3\x7d\x12\x9b\x75\x67\x46" }, { GCRY_MAC_CMAC_AES, "\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96\xe9\x3d\x7e\x11\x73\x93\x17\x2a", "\x2b\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c", "\x07\x0a\x16\xb4\x6b\x4d\x41\x44\xf7\x9b\xdd\x9d\xd0\x4a\x28\x7c" }, { GCRY_MAC_CMAC_AES, "\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96\xe9\x3d\x7e\x11\x73\x93\x17\x2a" "\xae\x2d\x8a\x57\x1e\x03\xac\x9c\x9e\xb7\x6f\xac\x45\xaf\x8e\x51" "\x30\xc8\x1c\x46\xa3\x5c\xe4\x11", "\x2b\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c", "\xdf\xa6\x67\x47\xde\x9a\xe6\x30\x30\xca\x32\x61\x14\x97\xc8\x27" }, { GCRY_MAC_CMAC_AES, "\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96\xe9\x3d\x7e\x11\x73\x93\x17\x2a" "\xae\x2d\x8a\x57\x1e\x03\xac\x9c\x9e\xb7\x6f\xac\x45\xaf\x8e\x51" "\x30\xc8\x1c\x46\xa3\x5c\xe4\x11\xe5\xfb\xc1\x19\x1a\x0a\x52\xef" "\xf6\x9f\x24\x45\xdf\x4f\x9b\x17\xad\x2b\x41\x7b\xe6\x6c\x37\x10", "\x2b\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c", "\x51\xf0\xbe\xbf\x7e\x3b\x9d\x92\xfc\x49\x74\x17\x79\x36\x3c\xfe" }, { GCRY_MAC_CMAC_AES, "", "\x8e\x73\xb0\xf7\xda\x0e\x64\x52\xc8\x10\xf3\x2b\x80\x90\x79\xe5" "\x62\xf8\xea\xd2\x52\x2c\x6b\x7b", "\xd1\x7d\xdf\x46\xad\xaa\xcd\xe5\x31\xca\xc4\x83\xde\x7a\x93\x67" }, { GCRY_MAC_CMAC_AES, "\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96\xe9\x3d\x7e\x11\x73\x93\x17\x2a", "\x8e\x73\xb0\xf7\xda\x0e\x64\x52\xc8\x10\xf3\x2b\x80\x90\x79\xe5" "\x62\xf8\xea\xd2\x52\x2c\x6b\x7b", "\x9e\x99\xa7\xbf\x31\xe7\x10\x90\x06\x62\xf6\x5e\x61\x7c\x51\x84" }, { GCRY_MAC_CMAC_AES, "\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96\xe9\x3d\x7e\x11\x73\x93\x17\x2a" "\xae\x2d\x8a\x57\x1e\x03\xac\x9c\x9e\xb7\x6f\xac\x45\xaf\x8e\x51" "\x30\xc8\x1c\x46\xa3\x5c\xe4\x11", "\x8e\x73\xb0\xf7\xda\x0e\x64\x52\xc8\x10\xf3\x2b\x80\x90\x79\xe5" "\x62\xf8\xea\xd2\x52\x2c\x6b\x7b", "\x8a\x1d\xe5\xbe\x2e\xb3\x1a\xad\x08\x9a\x82\xe6\xee\x90\x8b\x0e" }, { GCRY_MAC_CMAC_AES, "\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96\xe9\x3d\x7e\x11\x73\x93\x17\x2a" "\xae\x2d\x8a\x57\x1e\x03\xac\x9c\x9e\xb7\x6f\xac\x45\xaf\x8e\x51" "\x30\xc8\x1c\x46\xa3\x5c\xe4\x11\xe5\xfb\xc1\x19\x1a\x0a\x52\xef" "\xf6\x9f\x24\x45\xdf\x4f\x9b\x17\xad\x2b\x41\x7b\xe6\x6c\x37\x10", "\x8e\x73\xb0\xf7\xda\x0e\x64\x52\xc8\x10\xf3\x2b\x80\x90\x79\xe5" "\x62\xf8\xea\xd2\x52\x2c\x6b\x7b", "\xa1\xd5\xdf\x0e\xed\x79\x0f\x79\x4d\x77\x58\x96\x59\xf3\x9a\x11" }, { GCRY_MAC_CMAC_AES, "", "\x60\x3d\xeb\x10\x15\xca\x71\xbe\x2b\x73\xae\xf0\x85\x7d\x77\x81" "\x1f\x35\x2c\x07\x3b\x61\x08\xd7\x2d\x98\x10\xa3\x09\x14\xdf\xf4", "\x02\x89\x62\xf6\x1b\x7b\xf8\x9e\xfc\x6b\x55\x1f\x46\x67\xd9\x83" }, { GCRY_MAC_CMAC_AES, "\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96\xe9\x3d\x7e\x11\x73\x93\x17\x2a", "\x60\x3d\xeb\x10\x15\xca\x71\xbe\x2b\x73\xae\xf0\x85\x7d\x77\x81" "\x1f\x35\x2c\x07\x3b\x61\x08\xd7\x2d\x98\x10\xa3\x09\x14\xdf\xf4", "\x28\xa7\x02\x3f\x45\x2e\x8f\x82\xbd\x4b\xf2\x8d\x8c\x37\xc3\x5c" }, { GCRY_MAC_CMAC_AES, "\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96\xe9\x3d\x7e\x11\x73\x93\x17\x2a" "\xae\x2d\x8a\x57\x1e\x03\xac\x9c\x9e\xb7\x6f\xac\x45\xaf\x8e\x51" "\x30\xc8\x1c\x46\xa3\x5c\xe4\x11", "\x60\x3d\xeb\x10\x15\xca\x71\xbe\x2b\x73\xae\xf0\x85\x7d\x77\x81" "\x1f\x35\x2c\x07\x3b\x61\x08\xd7\x2d\x98\x10\xa3\x09\x14\xdf\xf4", "\xaa\xf3\xd8\xf1\xde\x56\x40\xc2\x32\xf5\xb1\x69\xb9\xc9\x11\xe6" }, { GCRY_MAC_CMAC_AES, "\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96\xe9\x3d\x7e\x11\x73\x93\x17\x2a" "\xae\x2d\x8a\x57\x1e\x03\xac\x9c\x9e\xb7\x6f\xac\x45\xaf\x8e\x51" "\x30\xc8\x1c\x46\xa3\x5c\xe4\x11\xe5\xfb\xc1\x19\x1a\x0a\x52\xef" "\xf6\x9f\x24\x45\xdf\x4f\x9b\x17\xad\x2b\x41\x7b\xe6\x6c\x37\x10", "\x60\x3d\xeb\x10\x15\xca\x71\xbe\x2b\x73\xae\xf0\x85\x7d\x77\x81" "\x1f\x35\x2c\x07\x3b\x61\x08\xd7\x2d\x98\x10\xa3\x09\x14\xdf\xf4", "\xe1\x99\x21\x90\x54\x9f\x6e\xd5\x69\x6a\x2c\x05\x6c\x31\x54\x10" }, { GCRY_MAC_CMAC_AES, "?", "????????????????????????????????", "\x9f\x72\x73\x68\xb0\x49\x2e\xb1\x35\xa0\x1d\xf9\xa8\x0a\xf6\xee" }, { GCRY_MAC_CMAC_3DES, "", "\x8a\xa8\x3b\xf8\xcb\xda\x10\x62\x0b\xc1\xbf\x19\xfb\xb6\xcd\x58" "\xbc\x31\x3d\x4a\x37\x1c\xa8\xb5", "\xb7\xa6\x88\xe1\x22\xff\xaf\x95" }, { GCRY_MAC_CMAC_3DES, "\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96", "\x8a\xa8\x3b\xf8\xcb\xda\x10\x62\x0b\xc1\xbf\x19\xfb\xb6\xcd\x58" "\xbc\x31\x3d\x4a\x37\x1c\xa8\xb5", "\x8e\x8f\x29\x31\x36\x28\x37\x97" }, { GCRY_MAC_CMAC_3DES, "\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96\xe9\x3d\x7e\x11\x73\x93\x17\x2a" "\xae\x2d\x8a\x57", "\x8a\xa8\x3b\xf8\xcb\xda\x10\x62\x0b\xc1\xbf\x19\xfb\xb6\xcd\x58" "\xbc\x31\x3d\x4a\x37\x1c\xa8\xb5", "\x74\x3d\xdb\xe0\xce\x2d\xc2\xed" }, { GCRY_MAC_CMAC_3DES, "\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96\xe9\x3d\x7e\x11\x73\x93\x17\x2a" "\xae\x2d\x8a\x57\x1e\x03\xac\x9c\x9e\xb7\x6f\xac\x45\xaf\x8e\x51", "\x8a\xa8\x3b\xf8\xcb\xda\x10\x62\x0b\xc1\xbf\x19\xfb\xb6\xcd\x58" "\xbc\x31\x3d\x4a\x37\x1c\xa8\xb5", "\x33\xe6\xb1\x09\x24\x00\xea\xe5" }, { GCRY_MAC_CMAC_3DES, "", "\x4c\xf1\x51\x34\xa2\x85\x0d\xd5\x8a\x3d\x10\xba\x80\x57\x0d\x38" "\x4c\xf1\x51\x34\xa2\x85\x0d\xd5", "\xbd\x2e\xbf\x9a\x3b\xa0\x03\x61" }, { GCRY_MAC_CMAC_3DES, "\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96", "\x4c\xf1\x51\x34\xa2\x85\x0d\xd5\x8a\x3d\x10\xba\x80\x57\x0d\x38" "\x4c\xf1\x51\x34\xa2\x85\x0d\xd5", "\x4f\xf2\xab\x81\x3c\x53\xce\x83" }, { GCRY_MAC_CMAC_3DES, "\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96\xe9\x3d\x7e\x11\x73\x93\x17\x2a" "\xae\x2d\x8a\x57", "\x4c\xf1\x51\x34\xa2\x85\x0d\xd5\x8a\x3d\x10\xba\x80\x57\x0d\x38" "\x4c\xf1\x51\x34\xa2\x85\x0d\xd5", "\x62\xdd\x1b\x47\x19\x02\xbd\x4e" }, { GCRY_MAC_CMAC_3DES, "\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96\xe9\x3d\x7e\x11\x73\x93\x17\x2a" "\xae\x2d\x8a\x57\x1e\x03\xac\x9c\x9e\xb7\x6f\xac\x45\xaf\x8e\x51", "\x4c\xf1\x51\x34\xa2\x85\x0d\xd5\x8a\x3d\x10\xba\x80\x57\x0d\x38" "\x4c\xf1\x51\x34\xa2\x85\x0d\xd5", "\x31\xb1\xe4\x31\xda\xbc\x4e\xb8" }, { GCRY_MAC_CMAC_3DES, "?", "????????????????????????", "\xc1\x38\x13\xb2\x31\x8f\x3a\xdf" }, /* CMAC Camellia test vectors from http://tools.ietf.org/html/draft-kato-ipsec-camellia-cmac96and128-05 */ { GCRY_MAC_CMAC_CAMELLIA, "", "\x2b\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c", "\xba\x92\x57\x82\xaa\xa1\xf5\xd9\xa0\x0f\x89\x64\x80\x94\xfc\x71" }, { GCRY_MAC_CMAC_CAMELLIA, "\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96\xe9\x3d\x7e\x11\x73\x93\x17\x2a", "\x2b\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c", "\x6d\x96\x28\x54\xa3\xb9\xfd\xa5\x6d\x7d\x45\xa9\x5e\xe1\x79\x93" }, { GCRY_MAC_CMAC_CAMELLIA, "\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96\xe9\x3d\x7e\x11\x73\x93\x17\x2a" "\xae\x2d\x8a\x57\x1e\x03\xac\x9c\x9e\xb7\x6f\xac\x45\xaf\x8e\x51" "\x30\xc8\x1c\x46\xa3\x5c\xe4\x11", "\x2b\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c", "\x5c\x18\xd1\x19\xcc\xd6\x76\x61\x44\xac\x18\x66\x13\x1d\x9f\x22" }, { GCRY_MAC_CMAC_CAMELLIA, "\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96\xe9\x3d\x7e\x11\x73\x93\x17\x2a" "\xae\x2d\x8a\x57\x1e\x03\xac\x9c\x9e\xb7\x6f\xac\x45\xaf\x8e\x51" "\x30\xc8\x1c\x46\xa3\x5c\xe4\x11\xe5\xfb\xc1\x19\x1a\x0a\x52\xef" "\xf6\x9f\x24\x45\xdf\x4f\x9b\x17\xad\x2b\x41\x7b\xe6\x6c\x37\x10", "\x2b\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c", "\xc2\x69\x9a\x6e\xba\x55\xce\x9d\x93\x9a\x8a\x4e\x19\x46\x6e\xe9" }, { GCRY_MAC_CMAC_CAMELLIA, "?", "????????????????????????????????", "\xba\x8a\x5a\x8d\xa7\x54\x26\x83\x3e\xb1\x20\xb5\x45\xd0\x9f\x4e" }, /* http://csrc.nist.gov/groups/STM/cavp/documents/mac/gcmtestvectors.zip */ { GCRY_MAC_GMAC_AES, "", "\x11\x75\x4c\xd7\x2a\xec\x30\x9b\xf5\x2f\x76\x87\x21\x2e\x89\x57", "\x25\x03\x27\xc6\x74\xaa\xf4\x77\xae\xf2\x67\x57\x48\xcf\x69\x71", "\x3c\x81\x9d\x9a\x9b\xed\x08\x76\x15\x03\x0b\x65" }, { GCRY_MAC_GMAC_AES, "\x2b\x63\x26\x64\x29\x67\x4a\xb5\xe2\xea\xff\x63\x9c\x23\x14\x66" "\x2f\x92\x57\x4b\x29\x8f\x57\x7a\xcf\x7d\x6f\x99\x1a\x87\x92\x1f" "\xc2\x32\xea\xfc\xc7\xb1\x46\x48\x96\x63\x2d\x6c\x8a\xbe\x88\xc2" "\xcc\xa4\x04\xdb\xf8\x7c\x20\x6a\x19\xd3\x73\xed\x99\x50\x17\x34" "\x69\x13\x4d\x7c\x14\xc2\x84\x7d\xf2\x4a\x88\xc1\xc5\x3b\x4d\xe4" "\x9d\xb3\x66\x39\x2b\x6d\xc6\x51\x27\x6e", "\x0f\x3b\x17\xde\xae\x62\x13\x64\x55\x4a\xe5\x39\xdb\x09\xde\x11", "\xff\xb0\xbb\x6d\xfc\x23\x58\x75\x4f\x17\x78\x48\x5b\x59\x65\x7f", "\xa7\xf6\x07\x4c\xda\x56\x1c\xd2\xaa\x15\xba\x8c\x2f\xa6\x39\x42" "\x59\x3e\x7c\xcf\x45\xc2\x9a\x57\xda\xd8\xa6\xe2\xea\x63\x54\xce" "\x8a\xde\x39\xdd\xde\x4a\xc4\x5b\xbd\xc6\x63\xf0\xa5\x37\xc9\x48" "\x18\x23\x5a\x73\xd8\xa0\x8b\xd8\x98\xab\xd0\x99\xe1\x5c\x08\x8c" "\x6e\x21\x17\x5a\xf4\xe9\xa4\x99\x70\x12\x82\xed\x32\x81\x50\xa6" "\xd9\x90\xe8\xec\x87\x85\xce\x26\x1b\xe1\xb8\x3f\xd8\x59\x1e\x57" "\x76\x5f\x3d\xc1\x11\x3f\xd0\x2a\x40\xf5\x01\x6a\xd0\xd0\xed\xc4" "\x92\x9a\x02\xe0\x17\xb2\xc5\xf4\x18\xd2\x96\xab\xd6\xc2\xea\x2e" }, { GCRY_MAC_GMAC_AES, "\x61\x14\x60\x11\x90\xf6\xef\x5e\x59\x23\x5d\xc0\x42\x8c\x09\xe3" "\x27\x0b\x19\xea", "\x15\xa4\x14\x46\x6a\x7f\x90\xea\x32\xbf\xd7\xf6\xe5\x8b\xfa\x06" "\xe9\x07\xfc\x41\x66\x89\xd9\x60\x39\x45\xd7\x94\x54\xd4\x23\x17", "\x19\x6e\x0e\x01\x0f\x08\x56\xf9\x82\xb4\x08\x92\x41\xd6\x24\x84", "\xab" }, { GCRY_MAC_GMAC_AES, "\x8b\x5c\x12\x4b\xef\x6e\x2f\x0f\xe4\xd8\xc9\x5c\xd5\xfa\x4c\xf1", "\x41\xc5\xda\x86\x67\xef\x72\x52\x20\xff\xe3\x9a\xe0\xac\x59\x0a" "\xc9\xfc\xa7\x29\xab\x60\xad\xa0", "\x20\x4b\xdb\x1b\xd6\x21\x54\xbf\x08\x92\x2a\xaa\x54\xee\xd7\x05", "\x05\xad\x13\xa5\xe2\xc2\xab\x66\x7e\x1a\x6f\xbc" }, { GCRY_MAC_GMAC_AES, "?", "????????????????????????????????", "\x84\x37\xc3\x42\xae\xf5\xd0\x40\xd3\x73\x90\xa9\x36\xed\x8a\x12" }, /* from NaCl */ { GCRY_MAC_POLY1305, "\x8e\x99\x3b\x9f\x48\x68\x12\x73\xc2\x96\x50\xba\x32\xfc\x76\xce" "\x48\x33\x2e\xa7\x16\x4d\x96\xa4\x47\x6f\xb8\xc5\x31\xa1\x18\x6a" "\xc0\xdf\xc1\x7c\x98\xdc\xe8\x7b\x4d\xa7\xf0\x11\xec\x48\xc9\x72" "\x71\xd2\xc2\x0f\x9b\x92\x8f\xe2\x27\x0d\x6f\xb8\x63\xd5\x17\x38" "\xb4\x8e\xee\xe3\x14\xa7\xcc\x8a\xb9\x32\x16\x45\x48\xe5\x26\xae" "\x90\x22\x43\x68\x51\x7a\xcf\xea\xbd\x6b\xb3\x73\x2b\xc0\xe9\xda" "\x99\x83\x2b\x61\xca\x01\xb6\xde\x56\x24\x4a\x9e\x88\xd5\xf9\xb3" "\x79\x73\xf6\x22\xa4\x3d\x14\xa6\x59\x9b\x1f\x65\x4c\xb4\x5a\x74" "\xe3\x55\xa5", "\xee\xa6\xa7\x25\x1c\x1e\x72\x91\x6d\x11\xc2\xcb\x21\x4d\x3c\x25" "\x25\x39\x12\x1d\x8e\x23\x4e\x65\x2d\x65\x1f\xa4\xc8\xcf\xf8\x80", "\xf3\xff\xc7\x70\x3f\x94\x00\xe5\x2a\x7d\xfb\x4b\x3d\x33\x05\xd9" }, /* from draft-nir-cfrg-chacha20-poly1305-03 */ { GCRY_MAC_POLY1305, "Cryptographic Forum Research Group", "\x85\xd6\xbe\x78\x57\x55\x6d\x33\x7f\x44\x52\xfe\x42\xd5\x06\xa8" "\x01\x03\x80\x8a\xfb\x0d\xb2\xfd\x4a\xbf\xf6\xaf\x41\x49\xf5\x1b", "\xa8\x06\x1d\xc1\x30\x51\x36\xc6\xc2\x2b\x8b\xaf\x0c\x01\x27\xa9" }, { GCRY_MAC_POLY1305, "'Twas brillig, and the slithy toves\n" "Did gyre and gimble in the wabe:\n" "All mimsy were the borogoves,\n" "And the mome raths outgrabe.", "\x1c\x92\x40\xa5\xeb\x55\xd3\x8a\xf3\x33\x88\x86\x04\xf6\xb5\xf0" "\x47\x39\x17\xc1\x40\x2b\x80\x09\x9d\xca\x5c\xbc\x20\x70\x75\xc0", "\x45\x41\x66\x9a\x7e\xaa\xee\x61\xe7\x08\xdc\x7c\xbc\xc5\xeb\x62" }, { GCRY_MAC_POLY1305, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", NULL, 191, 32 }, { GCRY_MAC_POLY1305, "Any submission to the IETF intended by the Contributor for " "publication as all or part of an IETF Internet-Draft or RFC and " "any statement made within the context of an IETF activity is " "considered an \"IETF Contribution\". Such statements include " "oral statements in IETF sessions, as well as written and " "electronic communications made at any time or place, which are " "addressed to", "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x36\xe5\xf6\xb5\xc5\xe0\x60\x70\xf0\xef\xca\x96\x22\x7a\x86\x3e", "\x36\xe5\xf6\xb5\xc5\xe0\x60\x70\xf0\xef\xca\x96\x22\x7a\x86\x3e", NULL, 0, 32 }, { GCRY_MAC_POLY1305, "Any submission to the IETF intended by the Contributor for " "publication as all or part of an IETF Internet-Draft or RFC and " "any statement made within the context of an IETF activity is " "considered an \"IETF Contribution\". Such statements include " "oral statements in IETF sessions, as well as written and " "electronic communications made at any time or place, which are " "addressed to", "\x36\xe5\xf6\xb5\xc5\xe0\x60\x70\xf0\xef\xca\x96\x22\x7a\x86\x3e" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\xf3\x47\x7e\x7c\xd9\x54\x17\xaf\x89\xa6\xb8\x79\x4c\x31\x0c\xf0", NULL, 0, 32 }, /* draft-irtf-cfrg-chacha20-poly1305-01 */ /* TV#5 */ { GCRY_MAC_POLY1305, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", "\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", NULL, 16, 32 }, /* TV#6 */ { GCRY_MAC_POLY1305, "\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", "\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", NULL, 16, 32 }, /* TV#7 */ { GCRY_MAC_POLY1305, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" "\xF0\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" "\x11\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", NULL, 48, 32 }, /* TV#8 */ { GCRY_MAC_POLY1305, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" "\xFB\xFE\xFE\xFE\xFE\xFE\xFE\xFE\xFE\xFE\xFE\xFE\xFE\xFE\xFE\xFE" "\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01", "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", NULL, 48, 32 }, /* TV#9 */ { GCRY_MAC_POLY1305, "\xFD\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", "\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\xFA\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", NULL, 16, 32 }, /* TV#10 */ { GCRY_MAC_POLY1305, "\xE3\x35\x94\xD7\x50\x5E\x43\xB9\x00\x00\x00\x00\x00\x00\x00\x00" "\x33\x94\xD7\x50\x5E\x43\x79\xCD\x01\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x01\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x14\x00\x00\x00\x00\x00\x00\x00\x55\x00\x00\x00\x00\x00\x00\x00", NULL, 64, 32 }, /* TV#11 */ { GCRY_MAC_POLY1305, "\xE3\x35\x94\xD7\x50\x5E\x43\xB9\x00\x00\x00\x00\x00\x00\x00\x00" "\x33\x94\xD7\x50\x5E\x43\x79\xCD\x01\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x01\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "\x13\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", NULL, 48, 32 }, /* from http://cr.yp.to/mac/poly1305-20050329.pdf */ { GCRY_MAC_POLY1305, "\xf3\xf6", "\x85\x1f\xc4\x0c\x34\x67\xac\x0b\xe0\x5c\xc2\x04\x04\xf3\xf7\x00" "\x58\x0b\x3b\x0f\x94\x47\xbb\x1e\x69\xd0\x95\xb5\x92\x8b\x6d\xbc", "\xf4\xc6\x33\xc3\x04\x4f\xc1\x45\xf8\x4f\x33\x5c\xb8\x19\x53\xde", NULL, 0, 32 }, { GCRY_MAC_POLY1305, "", "\xa0\xf3\x08\x00\x00\xf4\x64\x00\xd0\xc7\xe9\x07\x6c\x83\x44\x03" "\xdd\x3f\xab\x22\x51\xf1\x1a\xc7\x59\xf0\x88\x71\x29\xcc\x2e\xe7", "\xdd\x3f\xab\x22\x51\xf1\x1a\xc7\x59\xf0\x88\x71\x29\xcc\x2e\xe7", NULL, 0, 32 }, { GCRY_MAC_POLY1305, "\x66\x3c\xea\x19\x0f\xfb\x83\xd8\x95\x93\xf3\xf4\x76\xb6\xbc\x24" "\xd7\xe6\x79\x10\x7e\xa2\x6a\xdb\x8c\xaf\x66\x52\xd0\x65\x61\x36", "\x48\x44\x3d\x0b\xb0\xd2\x11\x09\xc8\x9a\x10\x0b\x5c\xe2\xc2\x08" "\x83\x14\x9c\x69\xb5\x61\xdd\x88\x29\x8a\x17\x98\xb1\x07\x16\xef", "\x0e\xe1\xc1\x6b\xb7\x3f\x0f\x4f\xd1\x98\x81\x75\x3c\x01\xcd\xbe", NULL, 0, 32 }, { GCRY_MAC_POLY1305, "\xab\x08\x12\x72\x4a\x7f\x1e\x34\x27\x42\xcb\xed\x37\x4d\x94\xd1" "\x36\xc6\xb8\x79\x5d\x45\xb3\x81\x98\x30\xf2\xc0\x44\x91\xfa\xf0" "\x99\x0c\x62\xe4\x8b\x80\x18\xb2\xc3\xe4\xa0\xfa\x31\x34\xcb\x67" "\xfa\x83\xe1\x58\xc9\x94\xd9\x61\xc4\xcb\x21\x09\x5c\x1b\xf9", "\x12\x97\x6a\x08\xc4\x42\x6d\x0c\xe8\xa8\x24\x07\xc4\xf4\x82\x07" "\x80\xf8\xc2\x0a\xa7\x12\x02\xd1\xe2\x91\x79\xcb\xcb\x55\x5a\x57", "\x51\x54\xad\x0d\x2c\xb2\x6e\x01\x27\x4f\xc5\x11\x48\x49\x1f\x1b" }, { GCRY_MAC_POLY1305, "?", "????????????????????????????????", "\xc3\x88\xce\x8a\x52\xd6\xe7\x21\x86\xfa\xaa\x5d\x2d\x16\xf9\xa3" }, /* from http://cr.yp.to/mac/poly1305-20050329.pdf */ { GCRY_MAC_POLY1305_AES, "\xf3\xf6", "\xec\x07\x4c\x83\x55\x80\x74\x17\x01\x42\x5b\x62\x32\x35\xad\xd6" "\x85\x1f\xc4\x0c\x34\x67\xac\x0b\xe0\x5c\xc2\x04\x04\xf3\xf7\x00", "\xf4\xc6\x33\xc3\x04\x4f\xc1\x45\xf8\x4f\x33\x5c\xb8\x19\x53\xde", "\xfb\x44\x73\x50\xc4\xe8\x68\xc5\x2a\xc3\x27\x5c\xf9\xd4\x32\x7e", 0, 32 }, { GCRY_MAC_POLY1305_AES, "", "\x75\xde\xaa\x25\xc0\x9f\x20\x8e\x1d\xc4\xce\x6b\x5c\xad\x3f\xbf" "\xa0\xf3\x08\x00\x00\xf4\x64\x00\xd0\xc7\xe9\x07\x6c\x83\x44\x03", "\xdd\x3f\xab\x22\x51\xf1\x1a\xc7\x59\xf0\x88\x71\x29\xcc\x2e\xe7", "\x61\xee\x09\x21\x8d\x29\xb0\xaa\xed\x7e\x15\x4a\x2c\x55\x09\xcc", 0, 32 }, { GCRY_MAC_POLY1305_AES, "\x66\x3c\xea\x19\x0f\xfb\x83\xd8\x95\x93\xf3\xf4\x76\xb6\xbc\x24" "\xd7\xe6\x79\x10\x7e\xa2\x6a\xdb\x8c\xaf\x66\x52\xd0\x65\x61\x36", "\x6a\xcb\x5f\x61\xa7\x17\x6d\xd3\x20\xc5\xc1\xeb\x2e\xdc\xdc\x74" "\x48\x44\x3d\x0b\xb0\xd2\x11\x09\xc8\x9a\x10\x0b\x5c\xe2\xc2\x08", "\x0e\xe1\xc1\x6b\xb7\x3f\x0f\x4f\xd1\x98\x81\x75\x3c\x01\xcd\xbe", "\xae\x21\x2a\x55\x39\x97\x29\x59\x5d\xea\x45\x8b\xc6\x21\xff\x0e", 0, 32 }, { GCRY_MAC_POLY1305_AES, "\xab\x08\x12\x72\x4a\x7f\x1e\x34\x27\x42\xcb\xed\x37\x4d\x94\xd1" "\x36\xc6\xb8\x79\x5d\x45\xb3\x81\x98\x30\xf2\xc0\x44\x91\xfa\xf0" "\x99\x0c\x62\xe4\x8b\x80\x18\xb2\xc3\xe4\xa0\xfa\x31\x34\xcb\x67" "\xfa\x83\xe1\x58\xc9\x94\xd9\x61\xc4\xcb\x21\x09\x5c\x1b\xf9", "\xe1\xa5\x66\x8a\x4d\x5b\x66\xa5\xf6\x8c\xc5\x42\x4e\xd5\x98\x2d" "\x12\x97\x6a\x08\xc4\x42\x6d\x0c\xe8\xa8\x24\x07\xc4\xf4\x82\x07", "\x51\x54\xad\x0d\x2c\xb2\x6e\x01\x27\x4f\xc5\x11\x48\x49\x1f\x1b", "\x9a\xe8\x31\xe7\x43\x97\x8d\x3a\x23\x52\x7c\x71\x28\x14\x9e\x3a", 0, 32 }, { GCRY_MAC_POLY1305_AES, "?", "????????????????????????????????", "\x9d\xeb\xb0\xcd\x24\x90\xd3\x9b\x47\x78\x37\x0a\x81\xf2\x83\x2a", "\x61\xee\x09\x21\x8d\x29\xb0\xaa\xed\x7e\x15\x4a\x2c\x55\x09\xcc", 0, 32 }, { 0 }, }; int i; if (verbose) fprintf (stderr, "Starting MAC checks.\n"); for (i = 0; algos[i].algo; i++) { size_t klen, dlen; if (gcry_mac_test_algo (algos[i].algo)) { show_mac_not_available (algos[i].algo); continue; } if (gcry_mac_test_algo (algos[i].algo) && in_fips_mode) { if (verbose) fprintf (stderr, " algorithm %d not available in fips mode\n", algos[i].algo); continue; } if (verbose) fprintf (stderr, " checking %s [%i] for %d byte key and %d byte data\n", gcry_mac_algo_name (algos[i].algo), algos[i].algo, (int)strlen(algos[i].key), (!strcmp(algos[i].data, "!") || !strcmp(algos[i].data, "?")) ? 1000000 : (int)strlen(algos[i].data)); klen = algos[i].klen ? algos[i].klen : strlen(algos[i].key); dlen = algos[i].dlen ? algos[i].dlen : strlen (algos[i].data); check_one_mac (algos[i].algo, algos[i].data, dlen, algos[i].key, klen, algos[i].iv, algos[i].iv ? strlen(algos[i].iv) : 0, algos[i].expect, 0); check_one_mac (algos[i].algo, algos[i].data, dlen, algos[i].key, klen, algos[i].iv, algos[i].iv ? strlen(algos[i].iv) : 0, algos[i].expect, 1); } if (verbose) fprintf (stderr, "Completed MAC checks.\n"); } /* Check that the signature SIG matches the hash HASH. PKEY is the public key used for the verification. BADHASH is a hash value which should result in a bad signature status. */ static void verify_one_signature (gcry_sexp_t pkey, gcry_sexp_t hash, gcry_sexp_t badhash, gcry_sexp_t sig) { gcry_error_t rc; rc = gcry_pk_verify (sig, hash, pkey); if (rc) fail ("gcry_pk_verify failed: %s\n", gpg_strerror (rc)); rc = gcry_pk_verify (sig, badhash, pkey); if (gcry_err_code (rc) != GPG_ERR_BAD_SIGNATURE) fail ("gcry_pk_verify failed to detect a bad signature: %s\n", gpg_strerror (rc)); } /* Test the public key sign function using the private ket SKEY. PKEY is used for verification. */ static void check_pubkey_sign (int n, gcry_sexp_t skey, gcry_sexp_t pkey, int algo) { gcry_error_t rc; gcry_sexp_t sig, badhash, hash; int dataidx; static const char baddata[] = "(data\n (flags pkcs1)\n" " (hash sha1 #11223344556677889900AABBCCDDEEFF10203041#))\n"; static const struct { const char *data; int algo; int expected_rc; } datas[] = { { "(data\n (flags pkcs1)\n" " (hash sha1 #11223344556677889900AABBCCDDEEFF10203040#))\n", GCRY_PK_RSA, 0 }, { "(data\n (flags pkcs1-raw)\n" " (hash sha1 #11223344556677889900AABBCCDDEEFF10203040#))\n", GCRY_PK_RSA, GPG_ERR_CONFLICT }, { "(data\n (flags oaep)\n" " (hash sha1 #11223344556677889900AABBCCDDEEFF10203040#))\n", 0, GPG_ERR_CONFLICT }, /* This test is to see whether hash algorithms not hard wired in pubkey.c are detected: */ { "(data\n (flags pkcs1)\n" " (hash oid.1.3.14.3.2.29 " " #11223344556677889900AABBCCDDEEFF10203040#))\n", GCRY_PK_RSA, 0 }, { "(data\n (flags )\n" " (hash sha1 #11223344556677889900AABBCCDDEEFF10203040#))\n", 0, GPG_ERR_CONFLICT }, { "(data\n (flags pkcs1)\n" " (hash foo #11223344556677889900AABBCCDDEEFF10203040#))\n", GCRY_PK_RSA, GPG_ERR_DIGEST_ALGO }, { "(data\n (flags )\n" " (value #11223344556677889900AA#))\n", 0, 0 }, { "(data\n (flags )\n" " (value #0090223344556677889900AA#))\n", 0, 0 }, { "(data\n (flags raw)\n" " (value #11223344556677889900AA#))\n", 0, 0 }, { "(data\n (flags pkcs1)\n" " (value #11223344556677889900AA#))\n", GCRY_PK_RSA, GPG_ERR_CONFLICT }, { "(data\n (flags pkcs1-raw)\n" " (value #11223344556677889900AA#))\n", GCRY_PK_RSA, 0 }, { "(data\n (flags raw foo)\n" " (value #11223344556677889900AA#))\n", 0, GPG_ERR_INV_FLAG }, { "(data\n (flags pss)\n" " (hash sha1 #11223344556677889900AABBCCDDEEFF10203040#))\n", GCRY_PK_RSA, 0 }, { "(data\n (flags pss)\n" " (hash sha1 #11223344556677889900AABBCCDDEEFF10203040#)\n" " (random-override #4253647587980912233445566778899019283747#))\n", GCRY_PK_RSA, 0 }, { NULL } }; rc = gcry_sexp_sscan (&badhash, NULL, baddata, strlen (baddata)); if (rc) die ("converting data failed: %s\n", gpg_strerror (rc)); for (dataidx = 0; datas[dataidx].data; dataidx++) { if (datas[dataidx].algo && datas[dataidx].algo != algo) continue; if (verbose) fprintf (stderr, " test %d, signature test %d (%s)\n", n, dataidx, gcry_pk_algo_name (algo)); rc = gcry_sexp_sscan (&hash, NULL, datas[dataidx].data, strlen (datas[dataidx].data)); if (rc) die ("converting data failed: %s\n", gpg_strerror (rc)); rc = gcry_pk_sign (&sig, hash, skey); if (gcry_err_code (rc) != datas[dataidx].expected_rc) fail ("gcry_pk_sign failed: %s\n", gpg_strerror (rc)); if (!rc) verify_one_signature (pkey, hash, badhash, sig); gcry_sexp_release (sig); sig = NULL; gcry_sexp_release (hash); hash = NULL; } gcry_sexp_release (badhash); } /* Test the public key sign function using the private ket SKEY. PKEY is used for verification. This variant is only used for ECDSA. */ static void check_pubkey_sign_ecdsa (int n, gcry_sexp_t skey, gcry_sexp_t pkey) { gcry_error_t rc; gcry_sexp_t sig, badhash, hash; unsigned int nbits; int dataidx; static const struct { unsigned int nbits; const char *data; int expected_rc; const char *baddata; int dummy; } datas[] = { { 192, "(data (flags raw)\n" " (value #00112233445566778899AABBCCDDEEFF0001020304050607#))", 0, "(data (flags raw)\n" " (value #80112233445566778899AABBCCDDEEFF0001020304050607#))", 0 }, { 256, "(data (flags raw)\n" " (value #00112233445566778899AABBCCDDEEFF" /* */ "000102030405060708090A0B0C0D0E0F#))", 0, "(data (flags raw)\n" " (value #80112233445566778899AABBCCDDEEFF" /* */ "000102030405060708090A0B0C0D0E0F#))", 0 }, { 256, "(data (flags raw)\n" " (hash sha256 #00112233445566778899AABBCCDDEEFF" /* */ "000102030405060708090A0B0C0D0E0F#))", 0, "(data (flags raw)\n" " (hash sha256 #80112233445566778899AABBCCDDEEFF" /* */ "000102030405060708090A0B0C0D0E0F#))", 0 }, { 256, "(data (flags gost)\n" " (value #00112233445566778899AABBCCDDEEFF" /* */ "000102030405060708090A0B0C0D0E0F#))", 0, "(data (flags gost)\n" " (value #80112233445566778899AABBCCDDEEFF" /* */ "000102030405060708090A0B0C0D0E0F#))", 0 }, { 512, "(data (flags gost)\n" " (value #00112233445566778899AABBCCDDEEFF" /* */ "000102030405060708090A0B0C0D0E0F" /* */ "000102030405060708090A0B0C0D0E0F" /* */ "000102030405060708090A0B0C0D0E0F#))", 0, "(data (flags gost)\n" " (value #80112233445566778899AABBCCDDEEFF" /* */ "000102030405060708090A0B0C0D0E0F" /* */ "000102030405060708090A0B0C0D0E0F" /* */ "000102030405060708090A0B0C0D0E0F#))", 0 }, { 0, NULL } }; nbits = gcry_pk_get_nbits (skey); for (dataidx = 0; datas[dataidx].data; dataidx++) { if (datas[dataidx].nbits != nbits) continue; if (verbose) fprintf (stderr, " test %d, signature test %d (%u bit ecdsa)\n", n, dataidx, nbits); rc = gcry_sexp_sscan (&hash, NULL, datas[dataidx].data, strlen (datas[dataidx].data)); if (rc) die ("converting data failed: %s\n", gpg_strerror (rc)); rc = gcry_sexp_sscan (&badhash, NULL, datas[dataidx].baddata, strlen (datas[dataidx].baddata)); if (rc) die ("converting data failed: %s\n", gpg_strerror (rc)); rc = gcry_pk_sign (&sig, hash, skey); if (gcry_err_code (rc) != datas[dataidx].expected_rc) fail ("gcry_pk_sign failed: %s\n", gpg_strerror (rc)); if (!rc && verbose > 1) show_sexp ("ECDSA signature:\n", sig); if (!rc) verify_one_signature (pkey, hash, badhash, sig); gcry_sexp_release (sig); sig = NULL; gcry_sexp_release (badhash); badhash = NULL; gcry_sexp_release (hash); hash = NULL; } } static void check_pubkey_crypt (int n, gcry_sexp_t skey, gcry_sexp_t pkey, int algo) { gcry_error_t rc; gcry_sexp_t plain = NULL; gcry_sexp_t ciph = NULL; gcry_sexp_t data = NULL; int dataidx; static const struct { int algo; /* If not 0 run test only if ALGO matches. */ const char *data; const char *hint; int unpadded; int encrypt_expected_rc; int decrypt_expected_rc; int special; } datas[] = { { GCRY_PK_RSA, "(data\n (flags pkcs1)\n" " (value #11223344556677889900AA#))\n", NULL, 0, 0, 0 }, { GCRY_PK_RSA, "(data\n (flags pkcs1)\n" " (value #11223344556677889900AA#))\n", "(flags pkcs1)", 1, 0, 0 }, { GCRY_PK_RSA, "(data\n (flags oaep)\n" " (value #11223344556677889900AA#))\n", "(flags oaep)", 1, 0, 0 }, { GCRY_PK_RSA, "(data\n (flags oaep)\n (hash-algo sha1)\n" " (value #11223344556677889900AA#))\n", "(flags oaep)(hash-algo sha1)", 1, 0, 0 }, { GCRY_PK_RSA, "(data\n (flags oaep)\n (hash-algo sha1)\n (label \"test\")\n" " (value #11223344556677889900AA#))\n", "(flags oaep)(hash-algo sha1)(label \"test\")", 1, 0, 0 }, { GCRY_PK_RSA, "(data\n (flags oaep)\n (hash-algo sha1)\n (label \"test\")\n" " (value #11223344556677889900AA#)\n" " (random-override #4253647587980912233445566778899019283747#))\n", "(flags oaep)(hash-algo sha1)(label \"test\")", 1, 0, 0 }, { 0, "(data\n (flags )\n" " (value #11223344556677889900AA#))\n", NULL, 1, 0, 0 }, { 0, "(data\n (flags )\n" " (value #0090223344556677889900AA#))\n", NULL, 1, 0, 0 }, { 0, "(data\n (flags raw)\n" " (value #11223344556677889900AA#))\n", NULL, 1, 0, 0 }, { GCRY_PK_RSA, "(data\n (flags pkcs1)\n" " (hash sha1 #11223344556677889900AABBCCDDEEFF10203040#))\n", NULL, 0, GPG_ERR_CONFLICT, 0}, { 0, "(data\n (flags raw foo)\n" " (hash sha1 #11223344556677889900AABBCCDDEEFF10203040#))\n", NULL, 0, GPG_ERR_INV_FLAG, 0}, { 0, "(data\n (flags raw)\n" " (value #11223344556677889900AA#))\n", "(flags oaep)", 1, 0, GPG_ERR_ENCODING_PROBLEM, 1 }, { GCRY_PK_RSA, "(data\n (flags oaep)\n" " (value #11223344556677889900AA#))\n", "(flags pkcs1)", 1, 0, GPG_ERR_ENCODING_PROBLEM, 1 }, { 0, "(data\n (flags pss)\n" " (value #11223344556677889900AA#))\n", NULL, 0, GPG_ERR_CONFLICT }, { 0, NULL } }; (void)n; for (dataidx = 0; datas[dataidx].data; dataidx++) { if (datas[dataidx].algo && datas[dataidx].algo != algo) continue; if (verbose) fprintf (stderr, " encryption/decryption test %d (algo %d)\n", dataidx, algo); rc = gcry_sexp_sscan (&data, NULL, datas[dataidx].data, strlen (datas[dataidx].data)); if (rc) die ("converting data failed: %s\n", gpg_strerror (rc)); rc = gcry_pk_encrypt (&ciph, data, pkey); if (gcry_err_code (rc) != datas[dataidx].encrypt_expected_rc) fail ("gcry_pk_encrypt failed: %s\n", gpg_strerror (rc)); if (!rc) { int expect_mismatch = 0; /* Insert decoding hint to CIPH. */ if (datas[dataidx].hint) { size_t hint_len, len; char *hint, *buf; gcry_sexp_t list; /* Convert decoding hint into canonical sexp. */ hint_len = gcry_sexp_new (&list, datas[dataidx].hint, strlen (datas[dataidx].hint), 1); hint_len = gcry_sexp_sprint (list, GCRYSEXP_FMT_CANON, NULL, 0); hint = gcry_malloc (hint_len); if (!hint) die ("can't allocate memory\n"); hint_len = gcry_sexp_sprint (list, GCRYSEXP_FMT_CANON, hint, hint_len); gcry_sexp_release (list); /* Convert CIPH into canonical sexp. */ len = gcry_sexp_sprint (ciph, GCRYSEXP_FMT_CANON, NULL, 0); buf = gcry_malloc (len + hint_len); if (!buf) die ("can't allocate memory\n"); len = gcry_sexp_sprint (ciph, GCRYSEXP_FMT_CANON, buf, len); /* assert (!strcmp (buf, "(7:enc-val", 10)); */ /* Copy decoding hint into CIPH. */ memmove (buf + 10 + hint_len, buf + 10, len - 10); memcpy (buf + 10, hint, hint_len); gcry_free (hint); gcry_sexp_new (&list, buf, len + hint_len, 1); gcry_free (buf); gcry_sexp_release (ciph); ciph = list; } rc = gcry_pk_decrypt (&plain, ciph, skey); if (!rc && datas[dataidx].special == 1) { /* It may happen that OAEP formatted data which is decrypted as pkcs#1 data returns a valid pkcs#1 frame. However, the returned value will not be identical - thus we expect a mismatch and test further on whether this mismatch actually happened. */ expect_mismatch = 1; } else if (gcry_err_code (rc) != datas[dataidx].decrypt_expected_rc) { if (verbose) { show_sexp (" data:\n", data); show_sexp (" ciph:\n", ciph); show_sexp (" key:\n", skey); } fail ("gcry_pk_decrypt failed: expected %d (%s), got %d (%s)\n", datas[dataidx].decrypt_expected_rc, gpg_strerror (datas[dataidx].decrypt_expected_rc), rc, gpg_strerror (rc)); } if (!rc && datas[dataidx].unpadded) { gcry_sexp_t p1, p2; p1 = gcry_sexp_find_token (data, "value", 0); p2 = gcry_sexp_find_token (plain, "value", 0); if (p1 && p2) { const char *s1, *s2; size_t n1, n2; s1 = gcry_sexp_nth_data (p1, 1, &n1); s2 = gcry_sexp_nth_data (p2, 1, &n2); if (n1 != n2 || memcmp (s1, s2, n1)) { if (expect_mismatch) expect_mismatch = 0; else fail ("gcry_pk_encrypt/gcry_pk_decrypt " "do not roundtrip\n"); } } if (expect_mismatch) fail ("gcry_pk_encrypt/gcry_pk_decrypt " "expected mismatch did not happen\n"); gcry_sexp_release (p1); gcry_sexp_release (p2); } } gcry_sexp_release (plain); plain = NULL; gcry_sexp_release (ciph); ciph = NULL; gcry_sexp_release (data); data = NULL; } } static void check_pubkey_grip (int n, const unsigned char *grip, gcry_sexp_t skey, gcry_sexp_t pkey, int algo) { unsigned char sgrip[20], pgrip[20]; (void)algo; if (!gcry_pk_get_keygrip (skey, sgrip)) die ("get keygrip for private RSA key failed\n"); if (!gcry_pk_get_keygrip (pkey, pgrip)) die ("[%i] get keygrip for public RSA key failed\n", n); if (memcmp (sgrip, pgrip, 20)) fail ("[%i] keygrips don't match\n", n); if (memcmp (sgrip, grip, 20)) fail ("wrong keygrip for RSA key\n"); } static void do_check_one_pubkey (int n, gcry_sexp_t skey, gcry_sexp_t pkey, const unsigned char *grip, int algo, int flags) { if (flags & FLAG_SIGN) { if (algo == GCRY_PK_ECDSA) check_pubkey_sign_ecdsa (n, skey, pkey); else check_pubkey_sign (n, skey, pkey, algo); } if (flags & FLAG_CRYPT) check_pubkey_crypt (n, skey, pkey, algo); if (grip && (flags & FLAG_GRIP)) check_pubkey_grip (n, grip, skey, pkey, algo); } static void check_one_pubkey (int n, test_spec_pubkey_t spec) { gcry_error_t err = GPG_ERR_NO_ERROR; gcry_sexp_t skey, pkey; err = gcry_sexp_sscan (&skey, NULL, spec.key.secret, strlen (spec.key.secret)); if (!err) err = gcry_sexp_sscan (&pkey, NULL, spec.key.public, strlen (spec.key.public)); if (err) die ("converting sample key failed: %s\n", gpg_strerror (err)); do_check_one_pubkey (n, skey, pkey, (const unsigned char*)spec.key.grip, spec.id, spec.flags); gcry_sexp_release (skey); gcry_sexp_release (pkey); } static void get_keys_new (gcry_sexp_t *pkey, gcry_sexp_t *skey) { gcry_sexp_t key_spec, key, pub_key, sec_key; int rc; if (verbose) fprintf (stderr, " generating RSA key:"); rc = gcry_sexp_new (&key_spec, in_fips_mode ? "(genkey (rsa (nbits 4:2048)))" : "(genkey (rsa (nbits 4:1024)(transient-key)))", 0, 1); if (rc) die ("error creating S-expression: %s\n", gpg_strerror (rc)); rc = gcry_pk_genkey (&key, key_spec); gcry_sexp_release (key_spec); if (rc) die ("error generating RSA key: %s\n", gpg_strerror (rc)); pub_key = gcry_sexp_find_token (key, "public-key", 0); if (! pub_key) die ("public part missing in key\n"); sec_key = gcry_sexp_find_token (key, "private-key", 0); if (! sec_key) die ("private part missing in key\n"); gcry_sexp_release (key); *pkey = pub_key; *skey = sec_key; } static void check_one_pubkey_new (int n) { gcry_sexp_t skey, pkey; get_keys_new (&pkey, &skey); do_check_one_pubkey (n, skey, pkey, NULL, GCRY_PK_RSA, FLAG_SIGN | FLAG_CRYPT); gcry_sexp_release (pkey); gcry_sexp_release (skey); } /* Run all tests for the public key functions. */ static void check_pubkey (void) { static const test_spec_pubkey_t pubkeys[] = { { GCRY_PK_RSA, FLAG_CRYPT | FLAG_SIGN, { "(private-key\n" " (rsa\n" " (n #00e0ce96f90b6c9e02f3922beada93fe50a875eac6bcc18bb9a9cf2e84965caa" " 2d1ff95a7f542465c6c0c19d276e4526ce048868a7a914fd343cc3a87dd74291" " ffc565506d5bbb25cbac6a0e2dd1f8bcaab0d4a29c2f37c950f363484bf269f7" " 891440464baf79827e03a36e70b814938eebdc63e964247be75dc58b014b7ea2" " 51#)\n" " (e #010001#)\n" " (d #046129F2489D71579BE0A75FE029BD6CDB574EBF57EA8A5B0FDA942CAB943B11" " 7D7BB95E5D28875E0F9FC5FCC06A72F6D502464DABDED78EF6B716177B83D5BD" " C543DC5D3FED932E59F5897E92E6F58A0F33424106A3B6FA2CBF877510E4AC21" " C3EE47851E97D12996222AC3566D4CCB0B83D164074ABF7DE655FC2446DA1781" " #)\n" " (p #00e861b700e17e8afe6837e7512e35b6ca11d0ae47d8b85161c67baf64377213" " fe52d772f2035b3ca830af41d8a4120e1c1c70d12cc22f00d28d31dd48a8d424" " f1#)\n" " (q #00f7a7ca5367c661f8e62df34f0d05c10c88e5492348dd7bddc942c9a8f369f9" " 35a07785d2db805215ed786e4285df1658eed3ce84f469b81b50d358407b4ad3" " 61#)\n" " (u #304559a9ead56d2309d203811a641bb1a09626bc8eb36fffa23c968ec5bd891e" " ebbafc73ae666e01ba7c8990bae06cc2bbe10b75e69fcacb353a6473079d8e9b" " #)))\n", "(public-key\n" " (rsa\n" " (n #00e0ce96f90b6c9e02f3922beada93fe50a875eac6bcc18bb9a9cf2e84965caa" " 2d1ff95a7f542465c6c0c19d276e4526ce048868a7a914fd343cc3a87dd74291" " ffc565506d5bbb25cbac6a0e2dd1f8bcaab0d4a29c2f37c950f363484bf269f7" " 891440464baf79827e03a36e70b814938eebdc63e964247be75dc58b014b7ea2" " 51#)\n" " (e #010001#)))\n", "\x32\x10\x0c\x27\x17\x3e\xf6\xe9\xc4\xe9" "\xa2\x5d\x3d\x69\xf8\x6d\x37\xa4\xf9\x39"} }, { GCRY_PK_DSA, FLAG_SIGN, { "(private-key\n" " (DSA\n" " (p #00AD7C0025BA1A15F775F3F2D673718391D00456978D347B33D7B49E7F32EDAB" " 96273899DD8B2BB46CD6ECA263FAF04A28903503D59062A8865D2AE8ADFB5191" " CF36FFB562D0E2F5809801A1F675DAE59698A9E01EFE8D7DCFCA084F4C6F5A44" " 44D499A06FFAEA5E8EF5E01F2FD20A7B7EF3F6968AFBA1FB8D91F1559D52D877" " 7B#)\n" " (q #00EB7B5751D25EBBB7BD59D920315FD840E19AEBF9#)\n" " (g #1574363387FDFD1DDF38F4FBE135BB20C7EE4772FB94C337AF86EA8E49666503" " AE04B6BE81A2F8DD095311E0217ACA698A11E6C5D33CCDAE71498ED35D13991E" " B02F09AB40BD8F4C5ED8C75DA779D0AE104BC34C960B002377068AB4B5A1F984" " 3FBA91F537F1B7CAC4D8DD6D89B0D863AF7025D549F9C765D2FC07EE208F8D15" " #)\n" " (y #64B11EF8871BE4AB572AA810D5D3CA11A6CDBC637A8014602C72960DB135BF46" " A1816A724C34F87330FC9E187C5D66897A04535CC2AC9164A7150ABFA8179827" " 6E45831AB811EEE848EBB24D9F5F2883B6E5DDC4C659DEF944DCFD80BF4D0A20" " 42CAA7DC289F0C5A9D155F02D3D551DB741A81695B74D4C8F477F9C7838EB0FB" " #)\n" " (x #11D54E4ADBD3034160F2CED4B7CD292A4EBF3EC0#)))\n", "(public-key\n" " (DSA\n" " (p #00AD7C0025BA1A15F775F3F2D673718391D00456978D347B33D7B49E7F32EDAB" " 96273899DD8B2BB46CD6ECA263FAF04A28903503D59062A8865D2AE8ADFB5191" " CF36FFB562D0E2F5809801A1F675DAE59698A9E01EFE8D7DCFCA084F4C6F5A44" " 44D499A06FFAEA5E8EF5E01F2FD20A7B7EF3F6968AFBA1FB8D91F1559D52D877" " 7B#)\n" " (q #00EB7B5751D25EBBB7BD59D920315FD840E19AEBF9#)\n" " (g #1574363387FDFD1DDF38F4FBE135BB20C7EE4772FB94C337AF86EA8E49666503" " AE04B6BE81A2F8DD095311E0217ACA698A11E6C5D33CCDAE71498ED35D13991E" " B02F09AB40BD8F4C5ED8C75DA779D0AE104BC34C960B002377068AB4B5A1F984" " 3FBA91F537F1B7CAC4D8DD6D89B0D863AF7025D549F9C765D2FC07EE208F8D15" " #)\n" " (y #64B11EF8871BE4AB572AA810D5D3CA11A6CDBC637A8014602C72960DB135BF46" " A1816A724C34F87330FC9E187C5D66897A04535CC2AC9164A7150ABFA8179827" " 6E45831AB811EEE848EBB24D9F5F2883B6E5DDC4C659DEF944DCFD80BF4D0A20" " 42CAA7DC289F0C5A9D155F02D3D551DB741A81695B74D4C8F477F9C7838EB0FB" " #)))\n", "\xc6\x39\x83\x1a\x43\xe5\x05\x5d\xc6\xd8" "\x4a\xa6\xf9\xeb\x23\xbf\xa9\x12\x2d\x5b" } }, { GCRY_PK_ELG, FLAG_SIGN | FLAG_CRYPT, { "(private-key\n" " (ELG\n" " (p #00B93B93386375F06C2D38560F3B9C6D6D7B7506B20C1773F73F8DE56E6CD65D" " F48DFAAA1E93F57A2789B168362A0F787320499F0B2461D3A4268757A7B27517" " B7D203654A0CD484DEC6AF60C85FEB84AAC382EAF2047061FE5DAB81A20A0797" " 6E87359889BAE3B3600ED718BE61D4FC993CC8098A703DD0DC942E965E8F18D2" " A7#)\n" " (g #05#)\n" " (y #72DAB3E83C9F7DD9A931FDECDC6522C0D36A6F0A0FEC955C5AC3C09175BBFF2B" " E588DB593DC2E420201BEB3AC17536918417C497AC0F8657855380C1FCF11C5B" " D20DB4BEE9BDF916648DE6D6E419FA446C513AAB81C30CB7B34D6007637BE675" " 56CE6473E9F9EE9B9FADD275D001563336F2186F424DEC6199A0F758F6A00FF4" " #)\n" " (x #03C28900087B38DABF4A0AB98ACEA39BB674D6557096C01D72E31C16BDD32214" " #)))\n", "(public-key\n" " (ELG\n" " (p #00B93B93386375F06C2D38560F3B9C6D6D7B7506B20C1773F73F8DE56E6CD65D" " F48DFAAA1E93F57A2789B168362A0F787320499F0B2461D3A4268757A7B27517" " B7D203654A0CD484DEC6AF60C85FEB84AAC382EAF2047061FE5DAB81A20A0797" " 6E87359889BAE3B3600ED718BE61D4FC993CC8098A703DD0DC942E965E8F18D2" " A7#)\n" " (g #05#)\n" " (y #72DAB3E83C9F7DD9A931FDECDC6522C0D36A6F0A0FEC955C5AC3C09175BBFF2B" " E588DB593DC2E420201BEB3AC17536918417C497AC0F8657855380C1FCF11C5B" " D20DB4BEE9BDF916648DE6D6E419FA446C513AAB81C30CB7B34D6007637BE675" " 56CE6473E9F9EE9B9FADD275D001563336F2186F424DEC6199A0F758F6A00FF4" " #)))\n", "\xa7\x99\x61\xeb\x88\x83\xd2\xf4\x05\xc8" "\x4f\xba\x06\xf8\x78\x09\xbc\x1e\x20\xe5" } }, { /* ECDSA test. */ GCRY_PK_ECDSA, FLAG_SIGN, { "(private-key\n" " (ecdsa\n" " (curve nistp192)\n" " (q #048532093BA023F4D55C0424FA3AF9367E05F309DC34CDC3FE" " C13CA9E617C6C8487BFF6A726E3C4F277913D97117939966#)\n" " (d #00D4EF27E32F8AD8E2A1C6DDEBB1D235A69E3CEF9BCE90273D#)))\n", "(public-key\n" " (ecdsa\n" " (curve nistp192)\n" " (q #048532093BA023F4D55C0424FA3AF9367E05F309DC34CDC3FE" " C13CA9E617C6C8487BFF6A726E3C4F277913D97117939966#)))\n", "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" } }, { /* ECDSA test with the public key algorithm given as "ecc". */ GCRY_PK_ECDSA, FLAG_SIGN, { "(private-key\n" " (ecdsa\n" " (curve nistp192)\n" " (q #048532093BA023F4D55C0424FA3AF9367E05F309DC34CDC3FE" " C13CA9E617C6C8487BFF6A726E3C4F277913D97117939966#)\n" " (d #00D4EF27E32F8AD8E2A1C6DDEBB1D235A69E3CEF9BCE90273D#)))\n", "(public-key\n" " (ecc\n" " (curve nistp192)\n" " (q #048532093BA023F4D55C0424FA3AF9367E05F309DC34CDC3FE" " C13CA9E617C6C8487BFF6A726E3C4F277913D97117939966#)))\n", "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" } }, { /* ECDSA test with the private key algorithm given as "ecc". */ GCRY_PK_ECDSA, FLAG_SIGN, { "(private-key\n" " (ecc\n" " (curve nistp192)\n" " (q #048532093BA023F4D55C0424FA3AF9367E05F309DC34CDC3FE" " C13CA9E617C6C8487BFF6A726E3C4F277913D97117939966#)\n" " (d #00D4EF27E32F8AD8E2A1C6DDEBB1D235A69E3CEF9BCE90273D#)))\n", "(public-key\n" " (ecdsa\n" " (curve nistp192)\n" " (q #048532093BA023F4D55C0424FA3AF9367E05F309DC34CDC3FE" " C13CA9E617C6C8487BFF6A726E3C4F277913D97117939966#)))\n", "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" } }, { /* ECDSA test with the key algorithms given as "ecc". */ GCRY_PK_ECDSA, FLAG_SIGN, { "(private-key\n" " (ecc\n" " (curve nistp192)\n" " (q #048532093BA023F4D55C0424FA3AF9367E05F309DC34CDC3FE" " C13CA9E617C6C8487BFF6A726E3C4F277913D97117939966#)\n" " (d #00D4EF27E32F8AD8E2A1C6DDEBB1D235A69E3CEF9BCE90273D#)))\n", "(public-key\n" " (ecc\n" " (curve nistp192)\n" " (q #048532093BA023F4D55C0424FA3AF9367E05F309DC34CDC3FE" " C13CA9E617C6C8487BFF6A726E3C4F277913D97117939966#)))\n", "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" } }, { /* ECDSA test 256 bit. */ GCRY_PK_ECDSA, FLAG_SIGN, { "(private-key\n" " (ecc\n" " (curve nistp256)\n" " (q #04D4F6A6738D9B8D3A7075C1E4EE95015FC0C9B7E4272D2B" " EB6644D3609FC781B71F9A8072F58CB66AE2F89BB1245187" " 3ABF7D91F9E1FBF96BF2F70E73AAC9A283#)\n" " (d #5A1EF0035118F19F3110FB81813D3547BCE1E5BCE77D1F74" " 4715E1D5BBE70378#)))\n", "(public-key\n" " (ecc\n" " (curve nistp256)\n" " (q #04D4F6A6738D9B8D3A7075C1E4EE95015FC0C9B7E4272D2B" " EB6644D3609FC781B71F9A8072F58CB66AE2F89BB1245187" " 3ABF7D91F9E1FBF96BF2F70E73AAC9A283#)))\n", "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" } }, { /* GOST R 34.10-2001/2012 test 256 bit. */ GCRY_PK_ECDSA, FLAG_SIGN, { "(private-key\n" " (ecc\n" " (curve GOST2001-test)\n" " (q #047F2B49E270DB6D90D8595BEC458B50C58585BA1D4E9B78" " 8F6689DBD8E56FD80B26F1B489D6701DD185C8413A977B3C" " BBAF64D1C593D26627DFFB101A87FF77DA#)\n" " (d #7A929ADE789BB9BE10ED359DD39A72C11B60961F49397EEE" " 1D19CE9891EC3B28#)))\n", "(public-key\n" " (ecc\n" " (curve GOST2001-test)\n" " (q #047F2B49E270DB6D90D8595BEC458B50C58585BA1D4E9B78" " 8F6689DBD8E56FD80B26F1B489D6701DD185C8413A977B3C" " BBAF64D1C593D26627DFFB101A87FF77DA#)))\n", "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" } }, { /* GOST R 34.10-2012 test 512 bit. */ GCRY_PK_ECDSA, FLAG_SIGN, { "(private-key\n" " (ecc\n" " (curve GOST2012-test)\n" " (q #04115DC5BC96760C7B48598D8AB9E740D4C4A85A65BE33C1" " 815B5C320C854621DD5A515856D13314AF69BC5B924C8B" " 4DDFF75C45415C1D9DD9DD33612CD530EFE137C7C90CD4" " 0B0F5621DC3AC1B751CFA0E2634FA0503B3D52639F5D7F" " B72AFD61EA199441D943FFE7F0C70A2759A3CDB84C114E" " 1F9339FDF27F35ECA93677BEEC#)\n" " (d #0BA6048AADAE241BA40936D47756D7C93091A0E851466970" " 0EE7508E508B102072E8123B2200A0563322DAD2827E2714" " A2636B7BFD18AADFC62967821FA18DD4#)))\n", "(public-key\n" " (ecc\n" " (curve GOST2012-test)\n" " (q #04115DC5BC96760C7B48598D8AB9E740D4C4A85A65BE33C1" " 815B5C320C854621DD5A515856D13314AF69BC5B924C8B" " 4DDFF75C45415C1D9DD9DD33612CD530EFE137C7C90CD4" " 0B0F5621DC3AC1B751CFA0E2634FA0503B3D52639F5D7F" " B72AFD61EA199441D943FFE7F0C70A2759A3CDB84C114E" " 1F9339FDF27F35ECA93677BEEC#)))\n" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" } }, { /* secp256k1 test 256 bit. */ GCRY_PK_ECDSA, FLAG_SIGN, { "(private-key\n" " (ecc\n" " (curve secp256k1)\n" " (q #0439A36013301597DAEF41FBE593A02CC513D0B55527EC2D" " F1050E2E8FF49C85C23CBE7DED0E7CE6A594896B8F62888F" " DBC5C8821305E2EA42BF01E37300116281#)\n" " (d #E8F32E723DECF4051AEFAC8E2C93C9C5B214313817CDB01A" " 1494B917C8436B35#)))\n", "(public-key\n" " (ecc\n" " (curve secp256k1)\n" " (q #0439A36013301597DAEF41FBE593A02CC513D0B55527EC2D" " F1050E2E8FF49C85C23CBE7DED0E7CE6A594896B8F62888F" " DBC5C8821305E2EA42BF01E37300116281#)))\n" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" } } }; int i; if (verbose) fprintf (stderr, "Starting public key checks.\n"); for (i = 0; i < sizeof (pubkeys) / sizeof (*pubkeys); i++) if (pubkeys[i].id) { if (gcry_pk_test_algo (pubkeys[i].id) && in_fips_mode) { if (verbose) fprintf (stderr, " algorithm %d not available in fips mode\n", pubkeys[i].id); continue; } check_one_pubkey (i, pubkeys[i]); } if (verbose) fprintf (stderr, "Completed public key checks.\n"); if (verbose) fprintf (stderr, "Starting additional public key checks.\n"); for (i = 0; i < sizeof (pubkeys) / sizeof (*pubkeys); i++) if (pubkeys[i].id) { if (gcry_pk_test_algo (pubkeys[i].id) && in_fips_mode) { if (verbose) fprintf (stderr, " algorithm %d not available in fips mode\n", pubkeys[i].id); continue; } check_one_pubkey_new (i); } if (verbose) fprintf (stderr, "Completed additional public key checks.\n"); } int main (int argc, char **argv) { gpg_error_t err; int last_argc = -1; int use_fips = 0; int selftest_only = 0; int pubkey_only = 0; int cipher_modes_only = 0; int loop = 0; unsigned int loopcount = 0; if (argc) { argc--; argv++; } while (argc && last_argc != argc ) { last_argc = argc; if (!strcmp (*argv, "--")) { argc--; argv++; break; } else if (!strcmp (*argv, "--verbose")) { verbose++; argc--; argv++; } else if (!strcmp (*argv, "--debug")) { verbose = debug = 1; argc--; argv++; } else if (!strcmp (*argv, "--fips")) { use_fips = 1; argc--; argv++; } else if (!strcmp (*argv, "--selftest")) { selftest_only = 1; verbose += 2; argc--; argv++; } else if (!strcmp (*argv, "--pubkey")) { pubkey_only = 1; argc--; argv++; } else if (!strcmp (*argv, "--cipher-modes")) { cipher_modes_only = 1; argc--; argv++; } else if (!strcmp (*argv, "--die")) { die_on_error = 1; argc--; argv++; } else if (!strcmp (*argv, "--loop")) { argc--; argv++; if (argc) { loop = atoi (*argv); argc--; argv++; } } else if (!strcmp (*argv, "--disable-hwf")) { argc--; argv++; if (argc) { if (gcry_control (GCRYCTL_DISABLE_HWF, *argv, NULL)) fprintf (stderr, PGM ": unknown hardware feature `%s' - option ignored\n", *argv); argc--; argv++; } } } xgcry_control (GCRYCTL_SET_VERBOSITY, (int)verbose); if (use_fips) xgcry_control (GCRYCTL_FORCE_FIPS_MODE, 0); /* Check that we test exactly our version - including the patchlevel. */ if (strcmp (GCRYPT_VERSION, gcry_check_version (NULL))) die ("version mismatch; pgm=%s, library=%s\n", GCRYPT_VERSION,gcry_check_version (NULL)); if ( gcry_fips_mode_active () ) in_fips_mode = 1; if (!in_fips_mode) xgcry_control (GCRYCTL_DISABLE_SECMEM, 0); if (verbose) gcry_set_progress_handler (progress_handler, NULL); xgcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); if (debug) xgcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1u, 0); /* No valuable keys are create, so we can speed up our RNG. */ xgcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); do { if (pubkey_only) check_pubkey (); else if (cipher_modes_only) { check_ciphers (); check_cipher_modes (); } else if (!selftest_only) { check_ciphers (); check_cipher_modes (); check_bulk_cipher_modes (); check_digests (); check_hmac (); check_mac (); check_pubkey (); } loopcount++; if (loop) { fprintf (stderr, "Test iteration %u completed.\n", loopcount); if (loop != -1) loop--; } } while (loop); if (in_fips_mode && !selftest_only) { /* If we are in fips mode do some more tests. */ gcry_md_hd_t md; /* First trigger a self-test. */ xgcry_control (GCRYCTL_FORCE_FIPS_MODE, 0); if (!gcry_control (GCRYCTL_OPERATIONAL_P, 0)) fail ("not in operational state after self-test\n"); /* Get us into the error state. */ err = gcry_md_open (&md, GCRY_MD_SHA1, 0); if (err) fail ("failed to open SHA-1 hash context: %s\n", gpg_strerror (err)); else { err = gcry_md_enable (md, GCRY_MD_SHA256); if (err) fail ("failed to add SHA-256 hash context: %s\n", gpg_strerror (err)); else { /* gcry_md_get_algo is only defined for a context with just one digest algorithm. With our setup it should put the oibrary intoerror state. */ fputs ("Note: Two lines with error messages follow " "- this is expected\n", stderr); gcry_md_get_algo (md); gcry_md_close (md); if (gcry_control (GCRYCTL_OPERATIONAL_P, 0)) fail ("expected error state but still in operational state\n"); else { /* Now run a self-test and to get back into operational state. */ xgcry_control (GCRYCTL_FORCE_FIPS_MODE, 0); if (!gcry_control (GCRYCTL_OPERATIONAL_P, 0)) fail ("did not reach operational after error " "and self-test\n"); } } } } else { /* If in standard mode, run selftests. */ if (gcry_control (GCRYCTL_SELFTEST, 0)) fail ("running self-test failed\n"); } if (verbose) fprintf (stderr, "\nAll tests completed. Errors: %i\n", error_count); if (in_fips_mode && !gcry_fips_mode_active ()) fprintf (stderr, "FIPS mode is not anymore active\n"); return error_count ? 1 : 0; } diff --git a/tests/bench-slope.c b/tests/bench-slope.c index 6d93ad2d..75e6e43d 100644 --- a/tests/bench-slope.c +++ b/tests/bench-slope.c @@ -1,2088 +1,2088 @@ /* bench-slope.c - for libgcrypt * Copyright (C) 2013 Jussi Kivilinna * * 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 . */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #ifdef _GCRYPT_IN_LIBGCRYPT # include "../src/gcrypt-int.h" # include "../compat/libcompat.h" #else # include #endif #ifndef STR #define STR(v) #v #define STR2(v) STR(v) #endif #define PGM "bench-slope" #include "t-common.h" static int verbose; static int csv_mode; static int unaligned_mode; static int num_measurement_repetitions; /* CPU Ghz value provided by user, allows constructing cycles/byte and other results. */ static double cpu_ghz = -1; /* Whether we are running as part of the regression test suite. */ static int in_regression_test; /* The name of the currently printed section. */ static char *current_section_name; /* The name of the currently printed algorithm. */ static char *current_algo_name; /* The name of the currently printed mode. */ static char *current_mode_name; /*************************************** Default parameters for measurements. */ /* Start at small buffer size, to get reasonable timer calibration for fast * implementations (AES-NI etc). Sixteen selected to support the largest block * size of current set cipher blocks. */ #define BUF_START_SIZE 16 /* From ~0 to ~4kbytes give comparable results with results from academia * (SUPERCOP). */ #define BUF_END_SIZE (BUF_START_SIZE + 4096) /* With 128 byte steps, we get (4096)/64 = 64 data points. */ #define BUF_STEP_SIZE 64 /* Number of repeated measurements at each data point. The median of these * measurements is selected as data point further analysis. */ #define NUM_MEASUREMENT_REPETITIONS 64 /**************************************************** High-resolution timers. */ /* This benchmarking module needs needs high resolution timer. */ #undef NO_GET_NSEC_TIME #if defined(_WIN32) struct nsec_time { LARGE_INTEGER perf_count; }; static void get_nsec_time (struct nsec_time *t) { BOOL ok; ok = QueryPerformanceCounter (&t->perf_count); assert (ok); } static double get_time_nsec_diff (struct nsec_time *start, struct nsec_time *end) { static double nsecs_per_count = 0.0; double nsecs; if (nsecs_per_count == 0.0) { LARGE_INTEGER perf_freq; BOOL ok; /* Get counts per second. */ ok = QueryPerformanceFrequency (&perf_freq); assert (ok); nsecs_per_count = 1.0 / perf_freq.QuadPart; nsecs_per_count *= 1000000.0 * 1000.0; /* sec => nsec */ assert (nsecs_per_count > 0.0); } nsecs = end->perf_count.QuadPart - start->perf_count.QuadPart; /* counts */ nsecs *= nsecs_per_count; /* counts * (nsecs / count) => nsecs */ return nsecs; } #elif defined(HAVE_CLOCK_GETTIME) struct nsec_time { struct timespec ts; }; static void get_nsec_time (struct nsec_time *t) { int err; err = clock_gettime (CLOCK_REALTIME, &t->ts); assert (err == 0); } static double get_time_nsec_diff (struct nsec_time *start, struct nsec_time *end) { double nsecs; nsecs = end->ts.tv_sec - start->ts.tv_sec; nsecs *= 1000000.0 * 1000.0; /* sec => nsec */ /* This way we don't have to care if tv_nsec unsigned or signed. */ if (end->ts.tv_nsec >= start->ts.tv_nsec) nsecs += end->ts.tv_nsec - start->ts.tv_nsec; else nsecs -= start->ts.tv_nsec - end->ts.tv_nsec; return nsecs; } #elif defined(HAVE_GETTIMEOFDAY) struct nsec_time { struct timeval tv; }; static void get_nsec_time (struct nsec_time *t) { int err; err = gettimeofday (&t->tv, NULL); assert (err == 0); } static double get_time_nsec_diff (struct nsec_time *start, struct nsec_time *end) { double nsecs; nsecs = end->tv.tv_sec - start->tv.tv_sec; nsecs *= 1000000; /* sec => µsec */ /* This way we don't have to care if tv_usec unsigned or signed. */ if (end->tv.tv_usec >= start->tv.tv_usec) nsecs += end->tv.tv_usec - start->tv.tv_usec; else nsecs -= start->tv.tv_usec - end->tv.tv_usec; nsecs *= 1000; /* µsec => nsec */ return nsecs; } #else #define NO_GET_NSEC_TIME 1 #endif /* If no high resolution timer found, provide dummy bench-slope. */ #ifdef NO_GET_NSEC_TIME int main (void) { /* No nsec timer => SKIP test. */ return 77; } #else /* !NO_GET_NSEC_TIME */ /********************************************** Slope benchmarking framework. */ struct bench_obj { const struct bench_ops *ops; unsigned int num_measure_repetitions; unsigned int min_bufsize; unsigned int max_bufsize; unsigned int step_size; void *priv; }; typedef int (*const bench_initialize_t) (struct bench_obj * obj); typedef void (*const bench_finalize_t) (struct bench_obj * obj); typedef void (*const bench_do_run_t) (struct bench_obj * obj, void *buffer, size_t buflen); struct bench_ops { bench_initialize_t initialize; bench_finalize_t finalize; bench_do_run_t do_run; }; double get_slope (double (*const get_x) (unsigned int idx, void *priv), void *get_x_priv, double y_points[], unsigned int npoints, double *overhead) { double sumx, sumy, sumx2, sumy2, sumxy; unsigned int i; double b, a; sumx = sumy = sumx2 = sumy2 = sumxy = 0; for (i = 0; i < npoints; i++) { double x, y; x = get_x (i, get_x_priv); /* bytes */ y = y_points[i]; /* nsecs */ sumx += x; sumy += y; sumx2 += x * x; /*sumy2 += y * y;*/ sumxy += x * y; } b = (npoints * sumxy - sumx * sumy) / (npoints * sumx2 - sumx * sumx); a = (sumy - b * sumx) / npoints; if (overhead) *overhead = a; /* nsecs */ return b; /* nsecs per byte */ } double get_bench_obj_point_x (unsigned int idx, void *priv) { struct bench_obj *obj = priv; return (double) (obj->min_bufsize + (idx * obj->step_size)); } unsigned int get_num_measurements (struct bench_obj *obj) { unsigned int buf_range = obj->max_bufsize - obj->min_bufsize; unsigned int num = buf_range / obj->step_size + 1; while (obj->min_bufsize + (num * obj->step_size) > obj->max_bufsize) num--; return num + 1; } static int double_cmp (const void *_a, const void *_b) { const double *a, *b; a = _a; b = _b; if (*a > *b) return 1; if (*a < *b) return -1; return 0; } double do_bench_obj_measurement (struct bench_obj *obj, void *buffer, size_t buflen, double *measurement_raw, unsigned int loop_iterations) { const unsigned int num_repetitions = obj->num_measure_repetitions; const bench_do_run_t do_run = obj->ops->do_run; struct nsec_time start, end; unsigned int rep, loop; double res; if (num_repetitions < 1 || loop_iterations < 1) return 0.0; for (rep = 0; rep < num_repetitions; rep++) { get_nsec_time (&start); for (loop = 0; loop < loop_iterations; loop++) do_run (obj, buffer, buflen); get_nsec_time (&end); measurement_raw[rep] = get_time_nsec_diff (&start, &end); } /* Return median of repeated measurements. */ qsort (measurement_raw, num_repetitions, sizeof (measurement_raw[0]), double_cmp); if (num_repetitions % 2 == 1) return measurement_raw[num_repetitions / 2]; res = measurement_raw[num_repetitions / 2] + measurement_raw[num_repetitions / 2 - 1]; return res / 2; } unsigned int adjust_loop_iterations_to_timer_accuracy (struct bench_obj *obj, void *buffer, double *measurement_raw) { const double increase_thres = 3.0; double tmp, nsecs; unsigned int loop_iterations; unsigned int test_bufsize; test_bufsize = obj->min_bufsize; if (test_bufsize == 0) test_bufsize += obj->step_size; loop_iterations = 0; do { /* Increase loop iterations until we get other results than zero. */ nsecs = do_bench_obj_measurement (obj, buffer, test_bufsize, measurement_raw, ++loop_iterations); } while (nsecs < 1.0 - 0.1); do { /* Increase loop iterations until we get reasonable increase for elapsed time. */ tmp = do_bench_obj_measurement (obj, buffer, test_bufsize, measurement_raw, ++loop_iterations); } while (tmp < nsecs * (increase_thres - 0.1)); return loop_iterations; } /* Benchmark and return linear regression slope in nanoseconds per byte. */ double do_slope_benchmark (struct bench_obj *obj) { unsigned int num_measurements; double *measurements = NULL; double *measurement_raw = NULL; double slope, overhead; unsigned int loop_iterations, midx, i; unsigned char *real_buffer = NULL; unsigned char *buffer; size_t cur_bufsize; int err; err = obj->ops->initialize (obj); if (err < 0) return -1; num_measurements = get_num_measurements (obj); measurements = calloc (num_measurements, sizeof (*measurements)); if (!measurements) goto err_free; measurement_raw = calloc (obj->num_measure_repetitions, sizeof (*measurement_raw)); if (!measurement_raw) goto err_free; if (num_measurements < 1 || obj->num_measure_repetitions < 1 || obj->max_bufsize < 1 || obj->min_bufsize > obj->max_bufsize) goto err_free; real_buffer = malloc (obj->max_bufsize + 128 + unaligned_mode); if (!real_buffer) goto err_free; /* Get aligned buffer */ buffer = real_buffer; buffer += 128 - ((real_buffer - (unsigned char *) 0) & (128 - 1)); if (unaligned_mode) buffer += unaligned_mode; /* Make buffer unaligned */ for (i = 0; i < obj->max_bufsize; i++) buffer[i] = 0x55 ^ (-i); /* Adjust number of loop iterations up to timer accuracy. */ loop_iterations = adjust_loop_iterations_to_timer_accuracy (obj, buffer, measurement_raw); /* Perform measurements */ for (midx = 0, cur_bufsize = obj->min_bufsize; cur_bufsize <= obj->max_bufsize; cur_bufsize += obj->step_size, midx++) { measurements[midx] = do_bench_obj_measurement (obj, buffer, cur_bufsize, measurement_raw, loop_iterations); measurements[midx] /= loop_iterations; } assert (midx == num_measurements); slope = get_slope (&get_bench_obj_point_x, obj, measurements, num_measurements, &overhead); free (measurement_raw); free (measurements); free (real_buffer); obj->ops->finalize (obj); return slope; err_free: if (measurement_raw) free (measurement_raw); if (measurements) free (measurements); if (real_buffer) free (real_buffer); obj->ops->finalize (obj); return -1; } /********************************************************** Printing results. */ static void double_to_str (char *out, size_t outlen, double value) { const char *fmt; if (value < 1.0) fmt = "%.3f"; else if (value < 100.0) fmt = "%.2f"; else fmt = "%.1f"; snprintf (out, outlen, fmt, value); } static void bench_print_result_csv (double nsecs_per_byte) { double cycles_per_byte, mbytes_per_sec; char nsecpbyte_buf[16]; char mbpsec_buf[16]; char cpbyte_buf[16]; *cpbyte_buf = 0; double_to_str (nsecpbyte_buf, sizeof (nsecpbyte_buf), nsecs_per_byte); /* If user didn't provide CPU speed, we cannot show cycles/byte results. */ if (cpu_ghz > 0.0) { cycles_per_byte = nsecs_per_byte * cpu_ghz; double_to_str (cpbyte_buf, sizeof (cpbyte_buf), cycles_per_byte); } mbytes_per_sec = (1000.0 * 1000.0 * 1000.0) / (nsecs_per_byte * 1024 * 1024); double_to_str (mbpsec_buf, sizeof (mbpsec_buf), mbytes_per_sec); /* We print two empty fields to allow for future enhancements. */ printf ("%s,%s,%s,,,%s,ns/B,%s,MiB/s,%s,c/B\n", current_section_name, current_algo_name? current_algo_name : "", current_mode_name? current_mode_name : "", nsecpbyte_buf, mbpsec_buf, cpbyte_buf); } static void bench_print_result_std (double nsecs_per_byte) { double cycles_per_byte, mbytes_per_sec; char nsecpbyte_buf[16]; char mbpsec_buf[16]; char cpbyte_buf[16]; double_to_str (nsecpbyte_buf, sizeof (nsecpbyte_buf), nsecs_per_byte); /* If user didn't provide CPU speed, we cannot show cycles/byte results. */ if (cpu_ghz > 0.0) { cycles_per_byte = nsecs_per_byte * cpu_ghz; double_to_str (cpbyte_buf, sizeof (cpbyte_buf), cycles_per_byte); } else strcpy (cpbyte_buf, "-"); mbytes_per_sec = (1000.0 * 1000.0 * 1000.0) / (nsecs_per_byte * 1024 * 1024); double_to_str (mbpsec_buf, sizeof (mbpsec_buf), mbytes_per_sec); printf ("%9s ns/B %9s MiB/s %9s c/B\n", nsecpbyte_buf, mbpsec_buf, cpbyte_buf); } static void bench_print_result (double nsecs_per_byte) { if (csv_mode) bench_print_result_csv (nsecs_per_byte); else bench_print_result_std (nsecs_per_byte); } static void bench_print_section (const char *section_name, const char *print_name) { if (csv_mode) { gcry_free (current_section_name); current_section_name = gcry_xstrdup (section_name); } else printf ("%s:\n", print_name); } static void bench_print_header (int algo_width, const char *algo_name) { if (csv_mode) { gcry_free (current_algo_name); current_algo_name = gcry_xstrdup (algo_name); } else { if (algo_width < 0) printf (" %-*s | ", -algo_width, algo_name); else printf (" %-*s | ", algo_width, algo_name); printf ("%14s %15s %13s\n", "nanosecs/byte", "mebibytes/sec", "cycles/byte"); } } static void bench_print_algo (int algo_width, const char *algo_name) { if (csv_mode) { gcry_free (current_algo_name); current_algo_name = gcry_xstrdup (algo_name); } else { if (algo_width < 0) printf (" %-*s | ", -algo_width, algo_name); else printf (" %-*s | ", algo_width, algo_name); } } static void bench_print_mode (int width, const char *mode_name) { if (csv_mode) { gcry_free (current_mode_name); current_mode_name = gcry_xstrdup (mode_name); } else { if (width < 0) printf (" %-*s | ", -width, mode_name); else printf (" %*s | ", width, mode_name); fflush (stdout); } } static void bench_print_footer (int algo_width) { if (!csv_mode) printf (" %-*s =\n", algo_width, ""); } /********************************************************* Cipher benchmarks. */ struct bench_cipher_mode { int mode; const char *name; struct bench_ops *ops; int algo; }; static int bench_encrypt_init (struct bench_obj *obj) { struct bench_cipher_mode *mode = obj->priv; gcry_cipher_hd_t hd; int err, keylen; obj->min_bufsize = BUF_START_SIZE; obj->max_bufsize = BUF_END_SIZE; obj->step_size = BUF_STEP_SIZE; obj->num_measure_repetitions = num_measurement_repetitions; err = gcry_cipher_open (&hd, mode->algo, mode->mode, 0); if (err) { fprintf (stderr, PGM ": error opening cipher `%s'\n", gcry_cipher_algo_name (mode->algo)); exit (1); } keylen = gcry_cipher_get_algo_keylen (mode->algo); if (keylen) { char key[keylen]; int i; for (i = 0; i < keylen; i++) key[i] = 0x33 ^ (11 - i); err = gcry_cipher_setkey (hd, key, keylen); if (err) { fprintf (stderr, PGM ": gcry_cipher_setkey failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hd); exit (1); } } else { fprintf (stderr, PGM ": failed to get key length for algorithm `%s'\n", gcry_cipher_algo_name (mode->algo)); gcry_cipher_close (hd); exit (1); } obj->priv = hd; return 0; } static void bench_encrypt_free (struct bench_obj *obj) { gcry_cipher_hd_t hd = obj->priv; gcry_cipher_close (hd); } static void bench_encrypt_do_bench (struct bench_obj *obj, void *buf, size_t buflen) { gcry_cipher_hd_t hd = obj->priv; int err; err = gcry_cipher_encrypt (hd, buf, buflen, buf, buflen); if (err) { fprintf (stderr, PGM ": gcry_cipher_encrypt failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hd); exit (1); } } static void bench_decrypt_do_bench (struct bench_obj *obj, void *buf, size_t buflen) { gcry_cipher_hd_t hd = obj->priv; int err; err = gcry_cipher_decrypt (hd, buf, buflen, buf, buflen); if (err) { fprintf (stderr, PGM ": gcry_cipher_encrypt failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hd); exit (1); } } static struct bench_ops encrypt_ops = { &bench_encrypt_init, &bench_encrypt_free, &bench_encrypt_do_bench }; static struct bench_ops decrypt_ops = { &bench_encrypt_init, &bench_encrypt_free, &bench_decrypt_do_bench }; static int bench_xts_encrypt_init (struct bench_obj *obj) { struct bench_cipher_mode *mode = obj->priv; gcry_cipher_hd_t hd; int err, keylen; /* For XTS, benchmark with typical data-unit size (512 byte sectors). */ obj->min_bufsize = 512; obj->max_bufsize = 16 * obj->min_bufsize; obj->step_size = obj->min_bufsize; obj->num_measure_repetitions = num_measurement_repetitions; err = gcry_cipher_open (&hd, mode->algo, mode->mode, 0); if (err) { fprintf (stderr, PGM ": error opening cipher `%s'\n", gcry_cipher_algo_name (mode->algo)); exit (1); } /* Double key-length for XTS. */ keylen = gcry_cipher_get_algo_keylen (mode->algo) * 2; if (keylen) { char key[keylen]; int i; for (i = 0; i < keylen; i++) key[i] = 0x33 ^ (11 - i); err = gcry_cipher_setkey (hd, key, keylen); if (err) { fprintf (stderr, PGM ": gcry_cipher_setkey failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hd); exit (1); } } else { fprintf (stderr, PGM ": failed to get key length for algorithm `%s'\n", gcry_cipher_algo_name (mode->algo)); gcry_cipher_close (hd); exit (1); } obj->priv = hd; return 0; } static void bench_xts_encrypt_do_bench (struct bench_obj *obj, void *buf, size_t buflen) { gcry_cipher_hd_t hd = obj->priv; unsigned int pos; static const char tweak[16] = { 0xff, 0xff, 0xfe, }; size_t sectorlen = obj->step_size; char *cbuf = buf; int err; gcry_cipher_setiv (hd, tweak, sizeof (tweak)); /* Process each sector separately. */ for (pos = 0; pos < buflen; pos += sectorlen, cbuf += sectorlen) { err = gcry_cipher_encrypt (hd, cbuf, sectorlen, cbuf, sectorlen); if (err) { fprintf (stderr, PGM ": gcry_cipher_encrypt failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hd); exit (1); } } } static void bench_xts_decrypt_do_bench (struct bench_obj *obj, void *buf, size_t buflen) { gcry_cipher_hd_t hd = obj->priv; unsigned int pos; static const char tweak[16] = { 0xff, 0xff, 0xfe, }; size_t sectorlen = obj->step_size; char *cbuf = buf; int err; gcry_cipher_setiv (hd, tweak, sizeof (tweak)); /* Process each sector separately. */ for (pos = 0; pos < buflen; pos += sectorlen, cbuf += sectorlen) { err = gcry_cipher_decrypt (hd, cbuf, sectorlen, cbuf, sectorlen); if (err) { fprintf (stderr, PGM ": gcry_cipher_encrypt failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hd); exit (1); } } } static struct bench_ops xts_encrypt_ops = { &bench_xts_encrypt_init, &bench_encrypt_free, &bench_xts_encrypt_do_bench }; static struct bench_ops xts_decrypt_ops = { &bench_xts_encrypt_init, &bench_encrypt_free, &bench_xts_decrypt_do_bench }; static void bench_ccm_encrypt_do_bench (struct bench_obj *obj, void *buf, size_t buflen) { gcry_cipher_hd_t hd = obj->priv; int err; char tag[8]; char nonce[11] = { 0x80, 0x01, }; u64 params[3]; gcry_cipher_setiv (hd, nonce, sizeof (nonce)); /* Set CCM lengths */ params[0] = buflen; params[1] = 0; /*aadlen */ params[2] = sizeof (tag); err = gcry_cipher_ctl (hd, GCRYCTL_SET_CCM_LENGTHS, params, sizeof (params)); if (err) { fprintf (stderr, PGM ": gcry_cipher_ctl failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hd); exit (1); } err = gcry_cipher_encrypt (hd, buf, buflen, buf, buflen); if (err) { fprintf (stderr, PGM ": gcry_cipher_encrypt failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hd); exit (1); } err = gcry_cipher_gettag (hd, tag, sizeof (tag)); if (err) { fprintf (stderr, PGM ": gcry_cipher_gettag failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hd); exit (1); } } static void bench_ccm_decrypt_do_bench (struct bench_obj *obj, void *buf, size_t buflen) { gcry_cipher_hd_t hd = obj->priv; int err; char tag[8] = { 0, }; char nonce[11] = { 0x80, 0x01, }; u64 params[3]; gcry_cipher_setiv (hd, nonce, sizeof (nonce)); /* Set CCM lengths */ params[0] = buflen; params[1] = 0; /*aadlen */ params[2] = sizeof (tag); err = gcry_cipher_ctl (hd, GCRYCTL_SET_CCM_LENGTHS, params, sizeof (params)); if (err) { fprintf (stderr, PGM ": gcry_cipher_ctl failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hd); exit (1); } err = gcry_cipher_decrypt (hd, buf, buflen, buf, buflen); if (err) { fprintf (stderr, PGM ": gcry_cipher_encrypt failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hd); exit (1); } err = gcry_cipher_checktag (hd, tag, sizeof (tag)); if (gpg_err_code (err) == GPG_ERR_CHECKSUM) err = gpg_error (GPG_ERR_NO_ERROR); if (err) { fprintf (stderr, PGM ": gcry_cipher_gettag failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hd); exit (1); } } static void bench_ccm_authenticate_do_bench (struct bench_obj *obj, void *buf, size_t buflen) { gcry_cipher_hd_t hd = obj->priv; int err; char tag[8] = { 0, }; char nonce[11] = { 0x80, 0x01, }; u64 params[3]; char data = 0xff; gcry_cipher_setiv (hd, nonce, sizeof (nonce)); /* Set CCM lengths */ params[0] = sizeof (data); /*datalen */ params[1] = buflen; /*aadlen */ params[2] = sizeof (tag); err = gcry_cipher_ctl (hd, GCRYCTL_SET_CCM_LENGTHS, params, sizeof (params)); if (err) { fprintf (stderr, PGM ": gcry_cipher_ctl failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hd); exit (1); } err = gcry_cipher_authenticate (hd, buf, buflen); if (err) { fprintf (stderr, PGM ": gcry_cipher_authenticate failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hd); exit (1); } err = gcry_cipher_encrypt (hd, &data, sizeof (data), &data, sizeof (data)); if (err) { fprintf (stderr, PGM ": gcry_cipher_encrypt failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hd); exit (1); } err = gcry_cipher_gettag (hd, tag, sizeof (tag)); if (err) { fprintf (stderr, PGM ": gcry_cipher_gettag failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hd); exit (1); } } static struct bench_ops ccm_encrypt_ops = { &bench_encrypt_init, &bench_encrypt_free, &bench_ccm_encrypt_do_bench }; static struct bench_ops ccm_decrypt_ops = { &bench_encrypt_init, &bench_encrypt_free, &bench_ccm_decrypt_do_bench }; static struct bench_ops ccm_authenticate_ops = { &bench_encrypt_init, &bench_encrypt_free, &bench_ccm_authenticate_do_bench }; static void bench_aead_encrypt_do_bench (struct bench_obj *obj, void *buf, size_t buflen, const char *nonce, size_t noncelen) { gcry_cipher_hd_t hd = obj->priv; int err; char tag[16]; gcry_cipher_setiv (hd, nonce, noncelen); gcry_cipher_final (hd); err = gcry_cipher_encrypt (hd, buf, buflen, buf, buflen); if (err) { fprintf (stderr, PGM ": gcry_cipher_encrypt failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hd); exit (1); } err = gcry_cipher_gettag (hd, tag, sizeof (tag)); if (err) { fprintf (stderr, PGM ": gcry_cipher_gettag failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hd); exit (1); } } static void bench_aead_decrypt_do_bench (struct bench_obj *obj, void *buf, size_t buflen, const char *nonce, size_t noncelen) { gcry_cipher_hd_t hd = obj->priv; int err; char tag[16] = { 0, }; gcry_cipher_setiv (hd, nonce, noncelen); gcry_cipher_final (hd); err = gcry_cipher_decrypt (hd, buf, buflen, buf, buflen); if (err) { fprintf (stderr, PGM ": gcry_cipher_encrypt failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hd); exit (1); } err = gcry_cipher_checktag (hd, tag, sizeof (tag)); if (gpg_err_code (err) == GPG_ERR_CHECKSUM) err = gpg_error (GPG_ERR_NO_ERROR); if (err) { fprintf (stderr, PGM ": gcry_cipher_gettag failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hd); exit (1); } } static void bench_aead_authenticate_do_bench (struct bench_obj *obj, void *buf, size_t buflen, const char *nonce, size_t noncelen) { gcry_cipher_hd_t hd = obj->priv; int err; char tag[16] = { 0, }; char data = 0xff; err = gcry_cipher_setiv (hd, nonce, noncelen); if (err) { fprintf (stderr, PGM ": gcry_cipher_setiv failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hd); exit (1); } err = gcry_cipher_authenticate (hd, buf, buflen); if (err) { fprintf (stderr, PGM ": gcry_cipher_authenticate failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hd); exit (1); } gcry_cipher_final (hd); err = gcry_cipher_encrypt (hd, &data, sizeof (data), &data, sizeof (data)); if (err) { fprintf (stderr, PGM ": gcry_cipher_encrypt failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hd); exit (1); } err = gcry_cipher_gettag (hd, tag, sizeof (tag)); if (err) { fprintf (stderr, PGM ": gcry_cipher_gettag failed: %s\n", gpg_strerror (err)); gcry_cipher_close (hd); exit (1); } } static void bench_gcm_encrypt_do_bench (struct bench_obj *obj, void *buf, size_t buflen) { char nonce[12] = { 0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad, 0xde, 0xca, 0xf8, 0x88 }; bench_aead_encrypt_do_bench (obj, buf, buflen, nonce, sizeof(nonce)); } static void bench_gcm_decrypt_do_bench (struct bench_obj *obj, void *buf, size_t buflen) { char nonce[12] = { 0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad, 0xde, 0xca, 0xf8, 0x88 }; bench_aead_decrypt_do_bench (obj, buf, buflen, nonce, sizeof(nonce)); } static void bench_gcm_authenticate_do_bench (struct bench_obj *obj, void *buf, size_t buflen) { char nonce[12] = { 0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad, 0xde, 0xca, 0xf8, 0x88 }; bench_aead_authenticate_do_bench (obj, buf, buflen, nonce, sizeof(nonce)); } static struct bench_ops gcm_encrypt_ops = { &bench_encrypt_init, &bench_encrypt_free, &bench_gcm_encrypt_do_bench }; static struct bench_ops gcm_decrypt_ops = { &bench_encrypt_init, &bench_encrypt_free, &bench_gcm_decrypt_do_bench }; static struct bench_ops gcm_authenticate_ops = { &bench_encrypt_init, &bench_encrypt_free, &bench_gcm_authenticate_do_bench }; static void bench_ocb_encrypt_do_bench (struct bench_obj *obj, void *buf, size_t buflen) { char nonce[15] = { 0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad, 0xde, 0xca, 0xf8, 0x88, 0x00, 0x00, 0x01 }; bench_aead_encrypt_do_bench (obj, buf, buflen, nonce, sizeof(nonce)); } static void bench_ocb_decrypt_do_bench (struct bench_obj *obj, void *buf, size_t buflen) { char nonce[15] = { 0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad, 0xde, 0xca, 0xf8, 0x88, 0x00, 0x00, 0x01 }; bench_aead_decrypt_do_bench (obj, buf, buflen, nonce, sizeof(nonce)); } static void bench_ocb_authenticate_do_bench (struct bench_obj *obj, void *buf, size_t buflen) { char nonce[15] = { 0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad, 0xde, 0xca, 0xf8, 0x88, 0x00, 0x00, 0x01 }; bench_aead_authenticate_do_bench (obj, buf, buflen, nonce, sizeof(nonce)); } static struct bench_ops ocb_encrypt_ops = { &bench_encrypt_init, &bench_encrypt_free, &bench_ocb_encrypt_do_bench }; static struct bench_ops ocb_decrypt_ops = { &bench_encrypt_init, &bench_encrypt_free, &bench_ocb_decrypt_do_bench }; static struct bench_ops ocb_authenticate_ops = { &bench_encrypt_init, &bench_encrypt_free, &bench_ocb_authenticate_do_bench }; static void bench_poly1305_encrypt_do_bench (struct bench_obj *obj, void *buf, size_t buflen) { char nonce[8] = { 0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad }; bench_aead_encrypt_do_bench (obj, buf, buflen, nonce, sizeof(nonce)); } static void bench_poly1305_decrypt_do_bench (struct bench_obj *obj, void *buf, size_t buflen) { char nonce[8] = { 0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad }; bench_aead_decrypt_do_bench (obj, buf, buflen, nonce, sizeof(nonce)); } static void bench_poly1305_authenticate_do_bench (struct bench_obj *obj, void *buf, size_t buflen) { char nonce[8] = { 0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad }; bench_aead_authenticate_do_bench (obj, buf, buflen, nonce, sizeof(nonce)); } static struct bench_ops poly1305_encrypt_ops = { &bench_encrypt_init, &bench_encrypt_free, &bench_poly1305_encrypt_do_bench }; static struct bench_ops poly1305_decrypt_ops = { &bench_encrypt_init, &bench_encrypt_free, &bench_poly1305_decrypt_do_bench }; static struct bench_ops poly1305_authenticate_ops = { &bench_encrypt_init, &bench_encrypt_free, &bench_poly1305_authenticate_do_bench }; static struct bench_cipher_mode cipher_modes[] = { {GCRY_CIPHER_MODE_ECB, "ECB enc", &encrypt_ops}, {GCRY_CIPHER_MODE_ECB, "ECB dec", &decrypt_ops}, {GCRY_CIPHER_MODE_CBC, "CBC enc", &encrypt_ops}, {GCRY_CIPHER_MODE_CBC, "CBC dec", &decrypt_ops}, {GCRY_CIPHER_MODE_CFB, "CFB enc", &encrypt_ops}, {GCRY_CIPHER_MODE_CFB, "CFB dec", &decrypt_ops}, {GCRY_CIPHER_MODE_OFB, "OFB enc", &encrypt_ops}, {GCRY_CIPHER_MODE_OFB, "OFB dec", &decrypt_ops}, {GCRY_CIPHER_MODE_CTR, "CTR enc", &encrypt_ops}, {GCRY_CIPHER_MODE_CTR, "CTR dec", &decrypt_ops}, {GCRY_CIPHER_MODE_XTS, "XTS enc", &xts_encrypt_ops}, {GCRY_CIPHER_MODE_XTS, "XTS dec", &xts_decrypt_ops}, {GCRY_CIPHER_MODE_CCM, "CCM enc", &ccm_encrypt_ops}, {GCRY_CIPHER_MODE_CCM, "CCM dec", &ccm_decrypt_ops}, {GCRY_CIPHER_MODE_CCM, "CCM auth", &ccm_authenticate_ops}, {GCRY_CIPHER_MODE_GCM, "GCM enc", &gcm_encrypt_ops}, {GCRY_CIPHER_MODE_GCM, "GCM dec", &gcm_decrypt_ops}, {GCRY_CIPHER_MODE_GCM, "GCM auth", &gcm_authenticate_ops}, {GCRY_CIPHER_MODE_OCB, "OCB enc", &ocb_encrypt_ops}, {GCRY_CIPHER_MODE_OCB, "OCB dec", &ocb_decrypt_ops}, {GCRY_CIPHER_MODE_OCB, "OCB auth", &ocb_authenticate_ops}, {GCRY_CIPHER_MODE_POLY1305, "POLY1305 enc", &poly1305_encrypt_ops}, {GCRY_CIPHER_MODE_POLY1305, "POLY1305 dec", &poly1305_decrypt_ops}, {GCRY_CIPHER_MODE_POLY1305, "POLY1305 auth", &poly1305_authenticate_ops}, {0}, }; static void cipher_bench_one (int algo, struct bench_cipher_mode *pmode) { struct bench_cipher_mode mode = *pmode; struct bench_obj obj = { 0 }; double result; unsigned int blklen; mode.algo = algo; /* Check if this mode is ok */ blklen = gcry_cipher_get_algo_blklen (algo); if (!blklen) return; /* Stream cipher? Only test with "ECB" and POLY1305. */ if (blklen == 1 && (mode.mode != GCRY_CIPHER_MODE_ECB && mode.mode != GCRY_CIPHER_MODE_POLY1305)) return; if (blklen == 1 && mode.mode == GCRY_CIPHER_MODE_ECB) { mode.mode = GCRY_CIPHER_MODE_STREAM; mode.name = mode.ops == &encrypt_ops ? "STREAM enc" : "STREAM dec"; } /* Poly1305 has restriction for cipher algorithm */ if (mode.mode == GCRY_CIPHER_MODE_POLY1305 && algo != GCRY_CIPHER_CHACHA20) return; /* CCM has restrictions for block-size */ if (mode.mode == GCRY_CIPHER_MODE_CCM && blklen != GCRY_CCM_BLOCK_LEN) return; /* GCM has restrictions for block-size */ if (mode.mode == GCRY_CIPHER_MODE_GCM && blklen != GCRY_GCM_BLOCK_LEN) return; /* XTS has restrictions for block-size */ if (mode.mode == GCRY_CIPHER_MODE_XTS && blklen != GCRY_XTS_BLOCK_LEN) return; - /* Our OCB implementaion has restrictions for block-size. */ + /* Our OCB implementation has restrictions for block-size. */ if (mode.mode == GCRY_CIPHER_MODE_OCB && blklen != GCRY_OCB_BLOCK_LEN) return; bench_print_mode (14, mode.name); obj.ops = mode.ops; obj.priv = &mode; result = do_slope_benchmark (&obj); bench_print_result (result); } static void _cipher_bench (int algo) { const char *algoname; int i; algoname = gcry_cipher_algo_name (algo); bench_print_header (14, algoname); for (i = 0; cipher_modes[i].mode; i++) cipher_bench_one (algo, &cipher_modes[i]); bench_print_footer (14); } void cipher_bench (char **argv, int argc) { int i, algo; bench_print_section ("cipher", "Cipher"); if (argv && argc) { for (i = 0; i < argc; i++) { algo = gcry_cipher_map_name (argv[i]); if (algo) _cipher_bench (algo); } } else { for (i = 1; i < 400; i++) if (!gcry_cipher_test_algo (i)) _cipher_bench (i); } } /*********************************************************** Hash benchmarks. */ struct bench_hash_mode { const char *name; struct bench_ops *ops; int algo; }; static int bench_hash_init (struct bench_obj *obj) { struct bench_hash_mode *mode = obj->priv; gcry_md_hd_t hd; int err; obj->min_bufsize = BUF_START_SIZE; obj->max_bufsize = BUF_END_SIZE; obj->step_size = BUF_STEP_SIZE; obj->num_measure_repetitions = num_measurement_repetitions; err = gcry_md_open (&hd, mode->algo, 0); if (err) { fprintf (stderr, PGM ": error opening hash `%s'\n", gcry_md_algo_name (mode->algo)); exit (1); } obj->priv = hd; return 0; } static void bench_hash_free (struct bench_obj *obj) { gcry_md_hd_t hd = obj->priv; gcry_md_close (hd); } static void bench_hash_do_bench (struct bench_obj *obj, void *buf, size_t buflen) { gcry_md_hd_t hd = obj->priv; gcry_md_reset (hd); gcry_md_write (hd, buf, buflen); gcry_md_final (hd); } static struct bench_ops hash_ops = { &bench_hash_init, &bench_hash_free, &bench_hash_do_bench }; static struct bench_hash_mode hash_modes[] = { {"", &hash_ops}, {0}, }; static void hash_bench_one (int algo, struct bench_hash_mode *pmode) { struct bench_hash_mode mode = *pmode; struct bench_obj obj = { 0 }; double result; mode.algo = algo; if (mode.name[0] == '\0') bench_print_algo (-14, gcry_md_algo_name (algo)); else bench_print_algo (14, mode.name); obj.ops = mode.ops; obj.priv = &mode; result = do_slope_benchmark (&obj); bench_print_result (result); } static void _hash_bench (int algo) { int i; for (i = 0; hash_modes[i].name; i++) hash_bench_one (algo, &hash_modes[i]); } void hash_bench (char **argv, int argc) { int i, algo; bench_print_section ("hash", "Hash"); bench_print_header (14, ""); if (argv && argc) { for (i = 0; i < argc; i++) { algo = gcry_md_map_name (argv[i]); if (algo) _hash_bench (algo); } } else { for (i = 1; i < 400; i++) if (!gcry_md_test_algo (i)) _hash_bench (i); } bench_print_footer (14); } /************************************************************ MAC benchmarks. */ struct bench_mac_mode { const char *name; struct bench_ops *ops; int algo; }; static int bench_mac_init (struct bench_obj *obj) { struct bench_mac_mode *mode = obj->priv; gcry_mac_hd_t hd; int err; unsigned int keylen; void *key; obj->min_bufsize = BUF_START_SIZE; obj->max_bufsize = BUF_END_SIZE; obj->step_size = BUF_STEP_SIZE; obj->num_measure_repetitions = num_measurement_repetitions; keylen = gcry_mac_get_algo_keylen (mode->algo); if (keylen == 0) keylen = 32; key = malloc (keylen); if (!key) { fprintf (stderr, PGM ": couldn't allocate %d bytes\n", keylen); exit (1); } memset(key, 42, keylen); err = gcry_mac_open (&hd, mode->algo, 0, NULL); if (err) { fprintf (stderr, PGM ": error opening mac `%s'\n", gcry_mac_algo_name (mode->algo)); free (key); exit (1); } err = gcry_mac_setkey (hd, key, keylen); if (err) { fprintf (stderr, PGM ": error setting key for mac `%s'\n", gcry_mac_algo_name (mode->algo)); free (key); exit (1); } switch (mode->algo) { default: break; case GCRY_MAC_POLY1305_AES: case GCRY_MAC_POLY1305_CAMELLIA: case GCRY_MAC_POLY1305_TWOFISH: case GCRY_MAC_POLY1305_SERPENT: case GCRY_MAC_POLY1305_SEED: gcry_mac_setiv (hd, key, 16); break; } obj->priv = hd; free (key); return 0; } static void bench_mac_free (struct bench_obj *obj) { gcry_mac_hd_t hd = obj->priv; gcry_mac_close (hd); } static void bench_mac_do_bench (struct bench_obj *obj, void *buf, size_t buflen) { gcry_mac_hd_t hd = obj->priv; size_t bs; char b; gcry_mac_reset (hd); gcry_mac_write (hd, buf, buflen); bs = sizeof(b); gcry_mac_read (hd, &b, &bs); } static struct bench_ops mac_ops = { &bench_mac_init, &bench_mac_free, &bench_mac_do_bench }; static struct bench_mac_mode mac_modes[] = { {"", &mac_ops}, {0}, }; static void mac_bench_one (int algo, struct bench_mac_mode *pmode) { struct bench_mac_mode mode = *pmode; struct bench_obj obj = { 0 }; double result; mode.algo = algo; if (mode.name[0] == '\0') bench_print_algo (-18, gcry_mac_algo_name (algo)); else bench_print_algo (18, mode.name); obj.ops = mode.ops; obj.priv = &mode; result = do_slope_benchmark (&obj); bench_print_result (result); } static void _mac_bench (int algo) { int i; for (i = 0; mac_modes[i].name; i++) mac_bench_one (algo, &mac_modes[i]); } void mac_bench (char **argv, int argc) { int i, algo; bench_print_section ("mac", "MAC"); bench_print_header (18, ""); if (argv && argc) { for (i = 0; i < argc; i++) { algo = gcry_mac_map_name (argv[i]); if (algo) _mac_bench (algo); } } else { for (i = 1; i < 600; i++) if (!gcry_mac_test_algo (i)) _mac_bench (i); } bench_print_footer (18); } /************************************************************ KDF benchmarks. */ struct bench_kdf_mode { struct bench_ops *ops; int algo; int subalgo; }; static int bench_kdf_init (struct bench_obj *obj) { struct bench_kdf_mode *mode = obj->priv; if (mode->algo == GCRY_KDF_PBKDF2) { obj->min_bufsize = 2; obj->max_bufsize = 2 * 32; obj->step_size = 2; } obj->num_measure_repetitions = num_measurement_repetitions; return 0; } static void bench_kdf_free (struct bench_obj *obj) { (void)obj; } static void bench_kdf_do_bench (struct bench_obj *obj, void *buf, size_t buflen) { struct bench_kdf_mode *mode = obj->priv; char keybuf[16]; (void)buf; if (mode->algo == GCRY_KDF_PBKDF2) { gcry_kdf_derive("qwerty", 6, mode->algo, mode->subalgo, "01234567", 8, buflen, sizeof(keybuf), keybuf); } } static struct bench_ops kdf_ops = { &bench_kdf_init, &bench_kdf_free, &bench_kdf_do_bench }; static void kdf_bench_one (int algo, int subalgo) { struct bench_kdf_mode mode = { &kdf_ops }; struct bench_obj obj = { 0 }; double nsecs_per_iteration; double cycles_per_iteration; char algo_name[32]; char nsecpiter_buf[16]; char cpiter_buf[16]; mode.algo = algo; mode.subalgo = subalgo; switch (subalgo) { case GCRY_MD_CRC32: case GCRY_MD_CRC32_RFC1510: case GCRY_MD_CRC24_RFC2440: case GCRY_MD_MD4: /* Skip CRC32s. */ return; } if (gcry_md_get_algo_dlen (subalgo) == 0) { /* Skip XOFs */ return; } *algo_name = 0; if (algo == GCRY_KDF_PBKDF2) { snprintf (algo_name, sizeof(algo_name), "PBKDF2-HMAC-%s", gcry_md_algo_name (subalgo)); } bench_print_algo (-24, algo_name); obj.ops = mode.ops; obj.priv = &mode; nsecs_per_iteration = do_slope_benchmark (&obj); strcpy(cpiter_buf, csv_mode ? "" : "-"); double_to_str (nsecpiter_buf, sizeof (nsecpiter_buf), nsecs_per_iteration); /* If user didn't provide CPU speed, we cannot show cycles/iter results. */ if (cpu_ghz > 0.0) { cycles_per_iteration = nsecs_per_iteration * cpu_ghz; double_to_str (cpiter_buf, sizeof (cpiter_buf), cycles_per_iteration); } if (csv_mode) { printf ("%s,%s,%s,,,,,,,,,%s,ns/iter,%s,c/iter\n", current_section_name, current_algo_name ? current_algo_name : "", current_mode_name ? current_mode_name : "", nsecpiter_buf, cpiter_buf); } else { printf ("%14s %13s\n", nsecpiter_buf, cpiter_buf); } } void kdf_bench (char **argv, int argc) { char algo_name[32]; int i, j; bench_print_section ("kdf", "KDF"); if (!csv_mode) { printf (" %-*s | ", 24, ""); printf ("%14s %13s\n", "nanosecs/iter", "cycles/iter"); } if (argv && argc) { for (i = 0; i < argc; i++) { for (j = 1; j < 400; j++) { if (gcry_md_test_algo (j)) continue; snprintf (algo_name, sizeof(algo_name), "PBKDF2-HMAC-%s", gcry_md_algo_name (j)); if (!strcmp(argv[i], algo_name)) kdf_bench_one (GCRY_KDF_PBKDF2, j); } } } else { for (i = 1; i < 400; i++) if (!gcry_md_test_algo (i)) kdf_bench_one (GCRY_KDF_PBKDF2, i); } bench_print_footer (24); } /************************************************************** Main program. */ void print_help (void) { static const char *help_lines[] = { "usage: bench-slope [options] [hash|mac|cipher|kdf [algonames]]", "", " options:", " --cpu-mhz Set CPU speed for calculating cycles", " per bytes results.", " --disable-hwf Disable hardware acceleration feature(s)", " for benchmarking.", " --repetitions Use N repetitions (default " STR2(NUM_MEASUREMENT_REPETITIONS) ")", " --unaligned Use unaligned input buffers.", " --csv Use CSV output format", NULL }; const char **line; for (line = help_lines; *line; line++) fprintf (stdout, "%s\n", *line); } /* Warm up CPU. */ static void warm_up_cpu (void) { struct nsec_time start, end; get_nsec_time (&start); do { get_nsec_time (&end); } while (get_time_nsec_diff (&start, &end) < 1000.0 * 1000.0 * 1000.0); } int main (int argc, char **argv) { int last_argc = -1; if (argc) { argc--; argv++; } /* We skip this test if we are running under the test suite (no args and srcdir defined) and GCRYPT_NO_BENCHMARKS is set. */ if (!argc && getenv ("srcdir") && getenv ("GCRYPT_NO_BENCHMARKS")) exit (77); if (getenv ("GCRYPT_IN_REGRESSION_TEST")) { in_regression_test = 1; num_measurement_repetitions = 2; } else num_measurement_repetitions = NUM_MEASUREMENT_REPETITIONS; while (argc && last_argc != argc) { last_argc = argc; if (!strcmp (*argv, "--")) { argc--; argv++; break; } else if (!strcmp (*argv, "--help")) { print_help (); exit (0); } else if (!strcmp (*argv, "--verbose")) { verbose++; argc--; argv++; } else if (!strcmp (*argv, "--debug")) { verbose += 2; debug++; argc--; argv++; } else if (!strcmp (*argv, "--csv")) { csv_mode = 1; argc--; argv++; } else if (!strcmp (*argv, "--unaligned")) { unaligned_mode = 1; argc--; argv++; } else if (!strcmp (*argv, "--disable-hwf")) { argc--; argv++; if (argc) { if (gcry_control (GCRYCTL_DISABLE_HWF, *argv, NULL)) fprintf (stderr, PGM ": unknown hardware feature `%s' - option ignored\n", *argv); argc--; argv++; } } else if (!strcmp (*argv, "--cpu-mhz")) { argc--; argv++; if (argc) { cpu_ghz = atof (*argv); cpu_ghz /= 1000; /* Mhz => Ghz */ argc--; argv++; } } else if (!strcmp (*argv, "--repetitions")) { argc--; argv++; if (argc) { num_measurement_repetitions = atof (*argv); if (num_measurement_repetitions < 2) { fprintf (stderr, PGM ": value for --repetitions too small - using %d\n", NUM_MEASUREMENT_REPETITIONS); num_measurement_repetitions = NUM_MEASUREMENT_REPETITIONS; } argc--; argv++; } } } xgcry_control (GCRYCTL_SET_VERBOSITY, (int) verbose); if (!gcry_check_version (GCRYPT_VERSION)) { fprintf (stderr, PGM ": version mismatch; pgm=%s, library=%s\n", GCRYPT_VERSION, gcry_check_version (NULL)); exit (1); } if (debug) xgcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1u, 0); xgcry_control (GCRYCTL_DISABLE_SECMEM, 0); xgcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); xgcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); if (in_regression_test) fputs ("Note: " PGM " running in quick regression test mode.\n", stdout); if (!argc) { warm_up_cpu (); hash_bench (NULL, 0); mac_bench (NULL, 0); cipher_bench (NULL, 0); kdf_bench (NULL, 0); } else if (!strcmp (*argv, "hash")) { argc--; argv++; warm_up_cpu (); hash_bench ((argc == 0) ? NULL : argv, argc); } else if (!strcmp (*argv, "mac")) { argc--; argv++; warm_up_cpu (); mac_bench ((argc == 0) ? NULL : argv, argc); } else if (!strcmp (*argv, "cipher")) { argc--; argv++; warm_up_cpu (); cipher_bench ((argc == 0) ? NULL : argv, argc); } else if (!strcmp (*argv, "kdf")) { argc--; argv++; warm_up_cpu (); kdf_bench ((argc == 0) ? NULL : argv, argc); } else { fprintf (stderr, PGM ": unknown argument: %s\n", *argv); print_help (); } return 0; } #endif /* !NO_GET_NSEC_TIME */ diff --git a/tests/cavs_driver.pl b/tests/cavs_driver.pl index b95e9b14..bc93feb9 100755 --- a/tests/cavs_driver.pl +++ b/tests/cavs_driver.pl @@ -1,2243 +1,2243 @@ #!/usr/bin/env perl # # $Id: cavs_driver.pl 1497 2009-01-22 14:01:29Z smueller $ # # CAVS test driver (based on the OpenSSL driver) # Written by: Stephan Müller # 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 .rep # 3. send the resulting 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) # KeyGen RSA X9.31 # # 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 # # DSA # PQGGen # SigGen # SigVer # # 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; # # Derive an RSA key from the given X9.31 parameters. # $1: modulus size # $2: E in hex form # $3: Xp1 in hex form # $4: Xp2 in hex form # $5: Xp in hex form # $6: Xq1 in hex form # $7: Xq2 in hex form # $8: Xq in hex form # return: string with the calculated values in hex format, where each value # is separated from the previous with a \n in the following order: # P\n # Q\n # N\n # D\n my $rsa_derive; # 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 == verified / 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; # the only difference of the DES version is that it implements the inner loop # of the TDES tests my $state_cipher_des; # 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; # # Generate the P, Q, G, Seed, counter, h (value used to generate g) values # for DSA # $1: modulus size # return: string with the calculated values in hex format, where each value # is separated from the previous with a \n in the following order: # P\n # Q\n # G\n # Seed\n # counter\n # h my $dsa_pqggen; # # Generate an DSA public key from the provided parameters: # $1: Name of file to create # $2: P in hex form # $3: Q in hex form # $4: G in hex form # $5: Y in hex form my $dsa_genpubkey; # Verify a message with DSA # $1: data to be verified in hex form # $2: file holding the public DSA key in PEM format # $3: R value of the signature # $4: S value of the signature # return: 1 == verified / 0 == not verified my $dsa_verify; # generate a new DSA key with the following properties: # PEM format # $1 keyfile name # return: file created, hash with keys of P, Q, G in hex format my $gen_dsakey; # Sign a message with DSA # $1: data to be signed in hex form # $2: Key file in PEM format with the private key # return: hash of digest information in hex format with Y, R, S as keys my $dsa_sign; ################################################################ ##### OpenSSL interface functions ################################################################ sub openssl_encdec($$$$$) { my $key=shift; my $iv=shift; my $cipher=shift; my $enc = (shift) ? "-e" : "-d"; my $data=shift; # We only invoke the driver with the IV parameter, if we have # an IV, otherwise, we skip it $iv = "-iv $iv" if ($iv); $data=hex2bin($data); my $program="openssl enc -$cipher -nopad -nosalt -K $key $enc $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"; # We only invoke the driver with the IV parameter, if we have # an IV, otherwise, we skip it $iv = "-iv ".bin2hex($iv) if ($iv); my $out = "openssl enc -'$cipher' $enc -nopad -nosalt -bufsize $bufsize -K ".bin2hex($key)." $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; # We only invoke the driver with the IV parameter, if we have # an IV, otherwise, we skip it $iv = "--iv $iv" if ($iv); my $program="fipsdrv --key $key $iv --algo $cipher $enc"; return pipe_through_program($data,$program); } sub libgcrypt_rsa_derive($$$$$$$$) { my $n = shift; my $e = shift; my $xp1 = shift; my $xp2 = shift; my $xp = shift; my $xq1 = shift; my $xq2 = shift; my $xq = shift; my $sexp; my @tmp; $n = sprintf ("%u", $n); $e = sprintf ("%u", hex($e)); $sexp = "(genkey(rsa(nbits " . sprintf ("%u:%s", length($n), $n) . ")" . "(rsa-use-e " . sprintf ("%u:%s", length($e), $e) . ")" . "(derive-parms" . "(Xp1 #$xp1#)" . "(Xp2 #$xp2#)" . "(Xp #$xp#)" . "(Xq1 #$xq1#)" . "(Xq2 #$xq2#)" . "(Xq #$xq#))))\n"; return pipe_through_program($sexp, "fipsdrv rsa-derive"); } 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 --pkcs1 --algo $hashalgo --key $keyfile rsa-sign"); } sub libgcrypt_rsa_verify($$$$) { my $data = shift; my $hashalgo = shift; my $keyfile = shift; my $sigfile = shift; die "ARCFOUR not available for RSA" if $opt{'R'}; $data = pipe_through_program($data, "fipsdrv --pkcs1 --algo $hashalgo --key $keyfile --signature $sigfile rsa-verify"); # Parse through the output information return ($data =~ /GOOD signature/); } 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 --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; # We only invoke the driver with the IV parameter, if we have # an IV, otherwise, we skip it $iv = "--iv ".bin2hex($iv) if ($iv); my $program="fipsdrv --binary --key ".bin2hex($key)." $iv --algo '$cipher' --chunk '$bufsize' $enc"; return $program; } sub libgcrypt_state_cipher_des($$$$$) { my $cipher = shift; my $enc = (shift) ? "encrypt": "decrypt"; my $bufsize = shift; my $key = shift; my $iv = shift; # We only invoke the driver with the IV parameter, if we have # an IV, otherwise, we skip it $iv = "--iv ".bin2hex($iv) if ($iv); my $program="fipsdrv --algo '$cipher' --mct-server $enc"; return $program; } sub libgcrypt_state_rng($$$) { my $key = shift; my $dt = shift; my $v = shift; return "fipsdrv --binary --loop --key $key --iv $v --dt $dt random"; } sub libgcrypt_hmac($$$$) { my $key = shift; my $maclen = shift; my $msg = shift; my $hashtype = shift; my $program = "fipsdrv --key $key --algo $hashtype hmac-sha"; return pipe_through_program($msg, $program); } sub libgcrypt_dsa_pqggen($) { my $mod = shift; my $program = "fipsdrv --keysize $mod dsa-pqg-gen"; return pipe_through_program("", $program); } sub libgcrypt_gen_dsakey($) { my $file = shift; my $program = "fipsdrv --keysize 1024 --key $file dsa-gen"; my $tmp; my %ret; die "ARCFOUR not available for DSA" if $opt{'R'}; $tmp = pipe_through_program("", $program); die "dsa key gen failed: file $file not created" if (! -f $file); @ret{'P', 'Q', 'G', 'Seed', 'c', 'H'} = split(/\n/, $tmp); return %ret; } sub libgcrypt_dsa_genpubkey($$$$$) { my $filename = shift; my $p = shift; my $q = shift; my $g = shift; my $y = shift; my $sexp; $sexp = "(public-key(dsa(p #$p#)(q #$q#)(g #$g#)(y #$y#)))"; open(FH, ">", $filename) or die; print FH $sexp; close FH; } sub libgcrypt_dsa_sign($$) { my $data = shift; my $keyfile = shift; my $tmp; my %ret; die "ARCFOUR not available for DSA" if $opt{'R'}; $tmp = pipe_through_program($data, "fipsdrv --key $keyfile dsa-sign"); @ret{'Y', 'R', 'S'} = split(/\n/, $tmp); return %ret; } sub libgcrypt_dsa_verify($$$$) { my $data = shift; my $keyfile = shift; my $r = shift; my $s = shift; my $ret; die "ARCFOUR not available for DSA" if $opt{'R'}; my $sigfile = "$keyfile.sig"; open(FH, ">$sigfile") or die "Cannot create file $sigfile: $?"; print FH "(sig-val(dsa(r #$r#)(s #$s#)))"; close FH; $ret = pipe_through_program($data, "fipsdrv --key $keyfile --signature $sigfile dsa-verify"); unlink ($sigfile); # Parse through the output information return ($ret =~ /GOOD signature/); } ######### End of libgcrypt implementation ################ ################################################################ ###### Vendor1 interface functions ################################################################ sub vendor1_encdec($$$$$) { my $key=shift; my $iv=shift; my $cipher=shift; my $enc = (shift) ? "encrypt" : "decrypt"; my $data=shift; $data=hex2bin($data); my $program = "./aes $enc $key"; $data=pipe_through_program($data,$program); return bin2hex($data); } sub vendor1_state_cipher($$$$$) { my $cipher = shift; my $encdec = shift; my $bufsize = shift; my $key = shift; my $iv = shift; $key = bin2hex($key); my $enc = $encdec ? "encrypt": "decrypt"; my $out = "./aes $enc $key $bufsize"; return $out; } ##### 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; } #################################################### # 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 (defined($iv) && $iv ne ""); if ($enc) { $out .= "PLAINTEXT = $pt\n"; $out .= "CIPHERTEXT = " . &$encdec($key1, $iv, $cipher, 1, $pt) . "\n"; } else { $out .= "CIPHERTEXT = $pt\n"; $out .= "PLAINTEXT = " . &$encdec($key1, $iv, $cipher, 0, $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"; $pt = "" if(!$len); $out .= "MD = " . &$hash($pt, $cipher) . "\n"; 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"; 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 (defined($iv) && $iv ne ""); 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); $cipher_imp = &$state_cipher_des($cipher, $enc, $bufsize, $key1, $iv) if($cipher =~ /des/); 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] my $next_source; # TDES inner loop implements logic within driver if ($cipher =~ /des/) { # Need to provide a dummy IV in case of ECB mode. my $iv_arg = (defined($iv) && $iv ne "") ? bin2hex($iv) : "00"x(length($source_data)); print $CI "1\n" .$iloop."\n" .bin2hex($key1)."\n" .$iv_arg."\n" .bin2hex($source_data)."\n\n" or die; chomp(my $line = <$CO>); $calc_data = hex2bin($line); chomp($line = <$CO>); $old_calc_data = hex2bin($line); chomp($line = <$CO>); $old_old_calc_data = hex2bin($line); chomp($line = <$CO>); $iv = hex2bin($line) if (defined($iv) && $iv ne ""); chomp($line = <$CO>); $next_source = hex2bin($line); # Skip over empty line. $line = <$CO>; } else { for (my $j = 0; $j < $iloop; ++$j) { $old_old_calc_data = $old_calc_data; $old_calc_data = $calc_data; #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"; die if $len ne $bufsize; #print STDERR "calc_data=", bin2hex($calc_data), "\n"; if ( (!$enc && $ciph =~ /des/) || $ciph =~ /rc4/ || $cipher =~ /ecb/ ) { #TDES in decryption mode, RC4 and ECB mode #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 ($cipher =~ /des-ede3-ofb/) { $source_data = $source_data ^ $next_source; } elsif (!$enc && $cipher =~ /des-ede3-cfb/) { #TDES decryption CFB has a special rule $source_data = $next_source; } elsif ( $ciph =~ /rc4/ || $cipher eq "des-ede3" || $cipher =~ /ecb/) { #No resetting of IV as the IV is all zero set initially (i.e. no IV) $source_data = $calc_data; } elsif (! $enc && $ciph =~ /des/ ) { #TDES in decryption mode has a special rule $iv = $old_calc_data; $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) { #print STDERR "outer loop $j; inner loop $i\n"; 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, lc($cipher), $keyfile) . "\n"; return $out; } # RSA SigVer test # $1: Message to be verified in hex form -# $2: Hash algoritm +# $2: Hash algorithm # $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, lc($cipher), $keyfile, $sigfile) ? "P\n" : "F\n"); unlink($keyfile); unlink($sigfile); return $out; } # RSA X9.31 key generation test # $1 modulus size # $2 e # $3 xp1 # $4 xp2 # $5 Xp # $6 xq1 # $7 xq2 # $8 Xq # return: string formatted as expected by CAVS sub rsa_keygen($$$$$$$$) { my $modulus = shift; my $e = shift; my $xp1 = shift; my $xp2 = shift; my $Xp = shift; my $xq1 = shift; my $xq2 = shift; my $Xq = shift; my $out = ""; my $ret = &$rsa_derive($modulus, $e, $xp1, $xp2, $Xp, $xq1, $xq2, $Xq); my ($P, $Q, $N, $D) = split(/\n/, $ret); $out .= "e = $e\n"; $out .= "xp1 = $xp1\n"; $out .= "xp2 = $xp2\n"; $out .= "Xp = $Xp\n"; $out .= "p = $P\n"; $out .= "xq1 = $xq1\n"; $out .= "xq2 = $xq2\n"; $out .= "Xq = $Xq\n"; $out .= "q = $Q\n"; $out .= "n = $N\n"; $out .= "d = $D\n\n"; 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; } # DSA PQGGen test # $1 modulus size # $2 number of rounds to perform the test # return: string formatted as expected by CAVS sub dsa_pqggen_driver($$) { my $mod = shift; my $rounds = shift; my $out = ""; for(my $i=0; $i<$rounds; $i++) { my $ret = &$dsa_pqggen($mod); my ($P, $Q, $G, $Seed, $c, $H) = split(/\n/, $ret); die "Return value does not contain all expected values of P, Q, G, Seed, c, H for dsa_pqggen" if (!defined($P) || !defined($Q) || !defined($G) || !defined($Seed) || !defined($c) || !defined($H)); # now change the counter to decimal as CAVS wants decimal # counter value although all other is HEX $c = hex($c); $out .= "P = $P\n"; $out .= "Q = $Q\n"; $out .= "G = $G\n"; $out .= "Seed = $Seed\n"; $out .= "c = $c\n"; $out .= "H = $H\n\n"; } return $out; } # DSA SigGen test # $1: Message to be signed in hex form # $2: file name with DSA key in PEM form # return: string formatted as expected by CAVS sub dsa_siggen($$) { my $data = shift; my $keyfile = shift; my $out = ""; my %ret = &$dsa_sign($data, $keyfile); $out .= "Msg = $data\n"; $out .= "Y = " . $ret{'Y'} . "\n"; $out .= "R = " . $ret{'R'} . "\n"; $out .= "S = " . $ret{'S'} . "\n"; return $out; } # DSA signature verification # $1 modulus # $2 P # $3 Q # $4 G # $5 Y - public key # $6 r # $7 s # $8 message to be verified # return: string formatted as expected by CAVS sub dsa_sigver($$$$$$$$) { my $modulus = shift; my $p = shift; my $q = shift; my $g = shift; my $y = shift; my $r = shift; my $s = shift; my $msg = shift; my $out = ""; #PQG are already printed - do not print them here $out .= "Msg = $msg\n"; $out .= "Y = $y\n"; $out .= "R = $r\n"; $out .= "S = $s\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 = "dsa_sigver.tmp.$$"; &$dsa_genpubkey($keyfile, $p, $q, $g, $y); $out .= "Result = " . (&$dsa_verify($msg, $keyfile, $r, $s) ? "P\n" : "F\n"); unlink($keyfile); return $out; } ############################################################## # Parser of input file and generator of result file # sub usage() { print STDERR "Usage: $0 [-R] [-D] [-I name] -R execution of ARCFOUR instead of OpenSSL -I NAME Use interface style NAME: openssl OpenSSL (default) libgcrypt Libgcrypt -D SigGen and SigVer are executed with DSA Please note that the DSA CAVS vectors do not allow distinguishing them from the RSA vectors. As the RSA test is the default, you have to supply this option to apply the DSA logic"; } # 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 = ""; # 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 $dsa_keyfile = ""; my $dt = ""; my $v = ""; my $klen = ""; my $tlen = ""; my $modulus = ""; my $capital_n = 0; my $capital_p = ""; my $capital_q = ""; my $capital_g = ""; my $capital_y = ""; my $capital_r = ""; my $xp1 = ""; my $xp2 = ""; my $Xp = ""; my $xq1 = ""; my $xq2 = ""; my $Xq = ""; my $mode = ""; open(IN, "<$infile"); while() { 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|PQGGen|KeyGen RSA)/) { 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 } 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"; } } if ($tt == 0) { ##### Identify the test type if ($tmpline =~ /KeyGen RSA \(X9\.31\)/) { $tt = 13; die "Interface function rsa_derive for RSA key generation not defined for tested library" if (!defined($rsa_derive)); } elsif ($tmpline =~ /SigVer/ && $opt{'D'} ) { $tt = 12; die "Interface function dsa_verify or dsa_genpubkey for DSA verification not defined for tested library" if (!defined($dsa_verify) || !defined($dsa_genpubkey)); } elsif ($tmpline =~ /SigGen/ && $opt{'D'}) { $tt = 11; die "Interface function dsa_sign or gen_dsakey for DSA sign not defined for tested library" if (!defined($dsa_sign) || !defined($gen_rsakey)); } elsif ($tmpline =~ /PQGGen/) { $tt = 10; die "Interface function for DSA PQGGen testing not defined for tested library" if (!defined($dsa_pqggen)); } elsif ($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 =~ /^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) || !defined($state_cipher_des)); } elsif ($cipher =~ /^sha/) { $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|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 =~ /^(KEYs)\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 $key2 = $key1; $key3 = $key1; } 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 $modulus = $1; $out .= $line . "\n\n"; # print it # generate the private key with given bit length now # as we have the required key length in bit if ($tt == 11) { $dsa_keyfile = "dsa_siggen.tmp.$$"; my %pqg = &$gen_dsakey($dsa_keyfile); $out .= "P = " . $pqg{'P'} . "\n"; $out .= "Q = " . $pqg{'Q'} . "\n"; $out .= "G = " . $pqg{'G'} . "\n"; } elsif ( $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($modulus, $rsa_keyfile); my $modulus = pipe_through_program("", "openssl rsa -pubout -modulus -in $rsa_keyfile"); $modulus =~ s/Modulus=(.*?)\s(.|\s)*/$1/; $out .= "n = $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; } elsif ($line =~ /^N\s*=\s*(.*)/) { #DSA PQGGen die "N seen twice - check input file" if ($capital_n); $capital_n = $1; } elsif ($line =~ /^P\s*=\s*(.*)/) { #DSA SigVer die "P seen twice - check input file" if ($capital_p); $capital_p = $1; $out .= $line . "\n"; # print it } elsif ($line =~ /^Q\s*=\s*(.*)/) { #DSA SigVer die "Q seen twice - check input file" if ($capital_q); $capital_q = $1; $out .= $line . "\n"; # print it } elsif ($line =~ /^G\s*=\s*(.*)/) { #DSA SigVer die "G seen twice - check input file" if ($capital_g); $capital_g = $1; $out .= $line . "\n"; # print it } elsif ($line =~ /^Y\s*=\s*(.*)/) { #DSA SigVer die "Y seen twice - check input file" if ($capital_y); $capital_y = $1; } elsif ($line =~ /^R\s*=\s*(.*)/) { #DSA SigVer die "R seen twice - check input file" if ($capital_r); $capital_r = $1; } elsif ($line =~ /^xp1\s*=\s*(.*)/) { #RSA key gen die "xp1 seen twice - check input file" if ($xp1); $xp1 = $1; } elsif ($line =~ /^xp2\s*=\s*(.*)/) { #RSA key gen die "xp2 seen twice - check input file" if ($xp2); $xp2 = $1; } elsif ($line =~ /^Xp\s*=\s*(.*)/) { #RSA key gen die "Xp seen twice - check input file" if ($Xp); $Xp = $1; } elsif ($line =~ /^xq1\s*=\s*(.*)/) { #RSA key gen die "xq1 seen twice - check input file" if ($xq1); $xq1 = $1; } elsif ($line =~ /^xq2\s*=\s*(.*)/) { #RSA key gen die "xq2 seen twice - check input file" if ($xq2); $xq2 = $1; } elsif ($line =~ /^Xq\s*=\s*(.*)/) { #RSA key gen die "Xq seen twice - check input file" if ($Xq); $Xq = $1; } else { $out .= $line . "\n"; } # call tests if all input data is there if ($tt == 1) { if ($key1 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 "" && $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 == 10) { if ($modulus ne "" && $capital_n > 0) { $out .= dsa_pqggen_driver($modulus, $capital_n); #$mod is not resetted $capital_n = 0; } } elsif ($tt == 11) { if ($pt ne "" && $dsa_keyfile ne "") { $out .= dsa_siggen($pt, $dsa_keyfile); $pt = ""; } } elsif ($tt == 12) { if ($modulus ne "" && $capital_p ne "" && $capital_q ne "" && $capital_g ne "" && $capital_y ne "" && $capital_r ne "" && $signature ne "" && $pt ne "") { $out .= dsa_sigver($modulus, $capital_p, $capital_q, $capital_g, $capital_y, $capital_r, $signature, $pt); # We do not clear the domain values PQG and # the modulus value as they # are specified only once in a file # and we do not need to print them as they # are already printed above $capital_y = ""; $capital_r = ""; $signature = ""; $pt = ""; } } elsif ($tt == 13) { if($modulus ne "" && $e ne "" && $xp1 ne "" && $xp2 ne "" && $Xp ne "" && $xq1 ne "" && $xq2 ne "" && $Xq ne "") { $out .= rsa_keygen($modulus, $e, $xp1, $xp2, $Xp, $xq1, $xq2, $Xq); $e = ""; $xp1 = ""; $xp2 = ""; $Xp = ""; $xq1 = ""; $xq2 = ""; $Xq = ""; } } 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"); unlink("dsa_siggen.tmp.$$"); unlink("dsa_sigver.tmp.$$"); unlink("dsa_sigver.tmp.$$.sig"); exit; } ############################################################ # # let us pretend to be C :-) sub main() { usage() unless @ARGV; getopts("DRI:", \%opt) or die "bad option"; ##### Set library 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; $rsa_derive = \&libgcrypt_rsa_derive; $hash = \&libgcrypt_hash; $state_cipher = \&libgcrypt_state_cipher; $state_cipher_des = \&libgcrypt_state_cipher_des; $state_rng = \&libgcrypt_state_rng; $hmac = \&libgcrypt_hmac; $dsa_pqggen = \&libgcrypt_dsa_pqggen; $gen_dsakey = \&libgcrypt_gen_dsakey; $dsa_sign = \&libgcrypt_dsa_sign; $dsa_verify = \&libgcrypt_dsa_verify; $dsa_genpubkey = \&libgcrypt_dsa_genpubkey; } 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); cleanup(); } ########################################### # Call it main(); 1; diff --git a/tests/hashtest.c b/tests/hashtest.c index d79d1042..2ecbc1f5 100644 --- a/tests/hashtest.c +++ b/tests/hashtest.c @@ -1,440 +1,440 @@ -/* hashtest.c - Check the hash fucntions +/* hashtest.c - Check the hash functions * Copyright (C) 2013 g10 Code GmbH * * 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 . */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #include "../src/gcrypt-int.h" #include "stopwatch.h" #define PGM "hashtest" #include "t-common.h" static int missing_test_vectors; static struct { int algo; int gigs; int bytes; const char *hex; } testvectors[] = { { GCRY_MD_SHA1, 256, -64, "92fc51850c7b750e6e774b75f294f6979d4059f0" }, { GCRY_MD_SHA1, 256, -1, "4bddeeb4c08683f02d4944d93dbcb02ebab50134" }, { GCRY_MD_SHA1, 256, -0, "71b923afde1c8c040884c723a2e3335b333e64c6" }, { GCRY_MD_SHA1, 256, 1, "2d99f9b5b86e9c9c937104f4242bd6b8bc0927ef" }, { GCRY_MD_SHA1, 256, 64, "a60dabe8d749f798b7ec3a684cc3eab487451482" }, { GCRY_MD_SHA224, 256, -64, "b5672b54d2480a5688a2dc727a1ad4db7a81ef31ce8999e0bbaeffdc" }, { GCRY_MD_SHA224, 256, -1, "814ea7159473e6ffc1c64b90026a542e13ac6980f7f3ca3c4582a9b8" }, { GCRY_MD_SHA224, 256, 0, "9ec0e1829455db8650ec7a8b06912196f97a7358bc3a73c79911cd4e" }, { GCRY_MD_SHA224, 256, 1, "e578d5d523320876565bbbc892511a485427caee6dd754d57e3e58c2" }, { GCRY_MD_SHA224, 256, 64, "ff0464df248cd298b63765bc4f87f21e25c93c657fdf3656d3c878e5" }, { GCRY_MD_SHA256, 256, -64, "87a9828d3de78d55d252341db2a622908c4e0ceaee9961ecf9768700fc799ec8" }, { GCRY_MD_SHA256, 256, -1, "823bf95f64ef04a4a77579c38760b1d401b56bf3a8e664bdf56ca15afb468a03" }, { GCRY_MD_SHA256, 256, 0, "2d0723878cb2c3d5c59dfad910cdb857f4430a6ba2a7d687938d7a20e63dde47" }, { GCRY_MD_SHA256, 256, 1, "5a2e21b1e79cd866acf53a2a18ca76bd4e02c4b01bf4627354171824c812d95f" }, { GCRY_MD_SHA256, 256, 64, "34444808af8e9d995e67f9e155ed94bf55f195a51dc1d8a989e6bcf95511c8a2" }, { GCRY_MD_SHA512, 256, -64, "e01bf8140874bf240e8426cb2bcbc377cbed2e6037334116637149e1cd8cd462" "96828b71f32b9f002771d4cb51172ce578b73b7939221e4df655ecd08601e655" }, { GCRY_MD_SHA512, 256, -1, "4917ff94514b1757705c289fdc3e7d6ffcce5771b20ae237ebc03d2ec9eb435f" "b7ce9f0e27272be8cced77a5edae1a01a0ad62b0a44169d88bbee45474a17734" }, { GCRY_MD_SHA512, 256, 0, "1e28e8b3c79f2f47da11f3c0b7da4e7981e7d932db6d17d528a31e191922edda" "8fc4bb2df10ea876232db5a1c606bc41886e8b2c570a3e721221f60c8c7dc4ab" }, { GCRY_MD_SHA512, 256, 1, "027d3324dd1cf127770ceb53681f4c70937c9bca4e3acd5fd76cb266c7d4527d" "58140290a1822e8d60c4d3ae9725fb923183230d6dfd2d7d73c0d74a4757f34a" }, { GCRY_MD_SHA512, 256, 64, "49920704ea9d6ee19f0742d6c868110fa3eda8ac09f026e9ef22cc731af53020" "de40eedef66cb1afd94c61e285fa9327e01336e804903740a9145ab1f065c2d5" }, { GCRY_MD_SHA3_512, 256, -64, "c6e082b3db996dbe5f2c5709818a7f325ef4febd883d7e9c545c06bfa7225198" "1ecf40103788913cd5a5bdf13246b952ded6651043684b24197eb23544882a97" }, { GCRY_MD_SHA3_512, 256, -1, "d7bf28e8216bf7d3d0d3969e34078e94b98598e17b6f21f256379389e4eba8ee" "74eb288774797263fec00bdfd357d132cea9e408be36b982f5a60ab56ad01613" }, { GCRY_MD_SHA3_512, 256, +0, "c1270852ba7b1e1a3eaa777969b8a65be28c3894537c61eb8cd22b1df6af703d" "b59939f6adadeb64317faece8167d4817e73daf73e28a5ccd26bebee0a35c322" }, { GCRY_MD_SHA3_512, 256, +1, "8bdfeb3a1a9a1cdcef21172cbc5bb3b87c0d8f7111df0aaf7f1bc03ad4775bd6" "a03e0a875c4e7d02d2230c213562c6a57be28d92eaf6e4bea4bc24690454c8ef" }, { GCRY_MD_SHA3_512, 256, +64, "0c91b91665ceaf7af5102e0ed31aa4f050668ab3c57b1f4763946d567efe66b3" "ab9a2016cf238dee5b44eae9f0cdfbf7b7a6eb1e759986273243dc35894706b6" }, { 0 } }; static void showhex (const void *buffer, size_t buflen, const char *format, ...) { va_list arg_ptr; const unsigned char *s; fprintf (stderr, "%s: ", PGM); va_start (arg_ptr, format); vfprintf (stderr, format, arg_ptr); va_end (arg_ptr); for (s=buffer; buflen; buflen--, s++) fprintf (stderr, "%02x", *s); putc ('\n', stderr); } static void show_note (const char *format, ...) { va_list arg_ptr; if (!verbose && getenv ("srcdir")) fputs (" ", stderr); /* To align above "PASS: ". */ else fprintf (stderr, "%s: ", PGM); va_start (arg_ptr, format); vfprintf (stderr, format, arg_ptr); if (*format && format[strlen(format)-1] != '\n') putc ('\n', stderr); va_end (arg_ptr); } /* 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 = 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; } static void run_selftest (int algo) { gpg_error_t err; size_t n; n = 1; err = gcry_md_algo_info (algo, GCRYCTL_SELFTEST, NULL, &n); if (err && gpg_err_code (err) != GPG_ERR_NOT_IMPLEMENTED) fail ("extended selftest for %s (%d) failed: %s", gcry_md_algo_name (algo), algo, gpg_strerror (err)); else if (err && verbose) info ("extended selftest for %s (%d) not implemented", gcry_md_algo_name (algo), algo); else if (verbose) info ("extended selftest for %s (%d) passed", gcry_md_algo_name (algo), algo); } /* Compare DIGEST of length DIGESTLEN generated using ALGO and GIGS plus BYTES with the test vector and print an error message if the don't match. Return 0 on match. */ static int cmp_digest (const unsigned char *digest, size_t digestlen, int algo, int gigs, int bytes) { int idx; unsigned char *tv_digest; size_t tv_digestlen = 0; for (idx=0; testvectors[idx].algo; idx++) { if (testvectors[idx].algo == algo && testvectors[idx].gigs == gigs && testvectors[idx].bytes == bytes) break; } if (!testvectors[idx].algo) { info ("%d GiB %+3d %-10s warning: %s", gigs, bytes, gcry_md_algo_name (algo), "no test vector"); missing_test_vectors++; return 1; } tv_digest = hex2buffer (testvectors[idx].hex, &tv_digestlen); if (tv_digestlen != digestlen) /* Ooops. */ { fail ("%d GiB %+3d %-10s error: %s", gigs, bytes, gcry_md_algo_name (algo), "digest length mismatch"); xfree (tv_digest); return 1; } if (memcmp (tv_digest, digest, tv_digestlen)) { fail ("%d GiB %+3d %-10s error: %s", gigs, bytes, gcry_md_algo_name (algo), "mismatch"); xfree (tv_digest); return 1; } xfree (tv_digest); return 0; } static void run_longtest (int algo, int gigs) { gpg_error_t err; gcry_md_hd_t hd; gcry_md_hd_t hd_pre = NULL; gcry_md_hd_t hd_pre2 = NULL; gcry_md_hd_t hd_post = NULL; gcry_md_hd_t hd_post2 = NULL; char pattern[1024]; int i, g; const unsigned char *digest; unsigned int digestlen; memset (pattern, 'a', sizeof pattern); err = gcry_md_open (&hd, algo, 0); if (err) { fail ("gcry_md_open failed for %s (%d): %s", gcry_md_algo_name (algo), algo, gpg_strerror (err)); return; } digestlen = gcry_md_get_algo_dlen (algo); for (g=0; g < gigs; g++) { if (g == gigs - 1) { for (i = 0; i < 1024*1023; i++) gcry_md_write (hd, pattern, sizeof pattern); for (i = 0; i < 1023; i++) gcry_md_write (hd, pattern, sizeof pattern); err = gcry_md_copy (&hd_pre, hd); if (!err) err = gcry_md_copy (&hd_pre2, hd); if (err) die ("gcry_md_copy failed for %s (%d): %s", gcry_md_algo_name (algo), algo, gpg_strerror (err)); gcry_md_write (hd, pattern, sizeof pattern); } else { for (i = 0; i < 1024*1024; i++) gcry_md_write (hd, pattern, sizeof pattern); } if (g && !(g % 16)) show_note ("%d GiB so far hashed with %s", g, gcry_md_algo_name (algo)); } if (g >= 16) show_note ("%d GiB hashed with %s", g, gcry_md_algo_name (algo)); err = gcry_md_copy (&hd_post, hd); if (err) die ("gcry_md_copy failed for %s (%d): %s", gcry_md_algo_name (algo), algo, gpg_strerror (err)); err = gcry_md_copy (&hd_post2, hd); if (err) die ("gcry_md_copy failed for %s (%d): %s", gcry_md_algo_name (algo), algo, gpg_strerror (err)); gcry_md_write (hd_pre2, pattern, sizeof pattern - 64); gcry_md_write (hd_pre, pattern, sizeof pattern - 1); gcry_md_write (hd_post, pattern, 1); gcry_md_write (hd_post2, pattern, 64); digest = gcry_md_read (hd_pre2, algo); if (cmp_digest (digest, digestlen, algo, gigs, -64) || verbose) showhex (digest, digestlen, "%d GiB %+3d %-10s ", gigs, -64, gcry_md_algo_name (algo)); digest = gcry_md_read (hd_pre, algo); if (cmp_digest (digest, digestlen, algo, gigs, -1) || verbose) showhex (digest, digestlen, "%d GiB %+3d %-10s ", gigs, -1, gcry_md_algo_name (algo)); digest = gcry_md_read (hd, algo); if (cmp_digest (digest, digestlen, algo, gigs, 0) || verbose) showhex (digest, digestlen, "%d GiB %+3d %-10s ", gigs, 0, gcry_md_algo_name (algo)); digest = gcry_md_read (hd_post, algo); if (cmp_digest (digest, digestlen, algo, gigs, 1) || verbose) showhex (digest, digestlen, "%d GiB %+3d %-10s ", gigs, 1, gcry_md_algo_name (algo)); digest = gcry_md_read (hd_post2, algo); if (cmp_digest (digest, digestlen, algo, gigs, 64) || verbose) showhex (digest, digestlen, "%d GiB %+3d %-10s ", gigs, 64, gcry_md_algo_name (algo)); gcry_md_close (hd); gcry_md_close (hd_pre); gcry_md_close (hd_pre2); gcry_md_close (hd_post); gcry_md_close (hd_post2); } int main (int argc, char **argv) { int last_argc = -1; int gigs = 0; int algo = 0; int idx; 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 " [options] [algos]\n" "Options:\n" " --verbose print timings etc.\n" " --debug flyswatter\n" " --gigs N Run a test on N GiB\n", stdout); exit (0); } else if (!strcmp (*argv, "--verbose")) { verbose++; argc--; argv++; } else if (!strcmp (*argv, "--debug")) { verbose += 2; debug++; argc--; argv++; } else if (!strcmp (*argv, "--gigs")) { argc--; argv++; if (argc) { gigs = atoi (*argv); argc--; argv++; } } else if (!strncmp (*argv, "--", 2)) die ("unknown option '%s'", *argv); } if (gigs < 0 || gigs > 1024*1024) die ("value for --gigs must be in the range 0 to %d", 1024*1024); xgcry_control (GCRYCTL_DISABLE_SECMEM, 0); if (!gcry_check_version (GCRYPT_VERSION)) die ("version mismatch\n"); if (debug) xgcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1u , 0); xgcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); xgcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); /* A quick check that all given algorithms are valid. */ for (idx=0; idx < argc; idx++) { algo = gcry_md_map_name (argv[idx]); if (!algo) fail ("invalid algorithm '%s'", argv[idx]); } if (error_count) exit (1); /* Start checking. */ start_timer (); if (!argc) { for (algo=1; algo < 400; algo++) if (!gcry_md_test_algo (algo)) { if (!gigs) run_selftest (algo); else run_longtest (algo, gigs); } } else { for (idx=0; idx < argc; idx++) { algo = gcry_md_map_name (argv[idx]); if (!algo) die ("invalid algorithm '%s'", argv[idx]); if (!gigs) run_selftest (algo); else run_longtest (algo, gigs); } } stop_timer (); if (missing_test_vectors) fail ("Some test vectors are missing"); if (verbose) info ("All tests completed in %s. Errors: %d\n", elapsed_time (1), error_count); return !!error_count; } diff --git a/tests/t-lock.c b/tests/t-lock.c index 679a5f1c..7e5732e0 100644 --- a/tests/t-lock.c +++ b/tests/t-lock.c @@ -1,458 +1,458 @@ /* t-lock.c - Check the lock functions * Copyright (C) 2014 g10 Code GmbH * * 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 . */ #if HAVE_CONFIG_H # include #endif #include #include #include #include #include #include #if HAVE_PTHREAD # include #endif #define PGM "t-lock" #include "t-common.h" #include "../src/gcrypt-testapi.h" /* Mingw requires us to include windows.h after winsock2.h which is included by gcrypt.h. */ #ifdef _WIN32 # include #endif #ifdef _WIN32 # define THREAD_RET_TYPE DWORD WINAPI # define THREAD_RET_VALUE 0 #else # define THREAD_RET_TYPE void * # define THREAD_RET_VALUE NULL #endif /* Number of threads to run. */ #define N_NONCE_THREADS 8 /* Number of interations. */ #define N_NONCE_ITERATIONS 1000 /* Requested nonce size. */ #define NONCE_SIZE 11 /* This tests works by having a a couple of accountant threads which do random transactions between accounts and a revision threads which checks that the balance of all accounts is invariant. The idea for this check is due to Bruno Haible. */ #define N_ACCOUNT 8 #define ACCOUNT_VALUE 42 static int account[N_ACCOUNT]; /* Number of transactions done by each accountant. */ #define N_TRANSACTIONS 1000 /* Number of accountants to run. */ #define N_ACCOUNTANTS 5 /* Maximum transaction value. A quite low value is used so that we would get an integer overflow. */ #define MAX_TRANSACTION_VALUE 50 /* Flag to tell the revision thread to finish. */ static volatile int stop_revision_thread; struct thread_arg_s { int no; }; /* Wrapper functions to access Libgcrypt's internal test lock. */ static void external_lock_test_init (int line) { gpg_error_t err; err = gcry_control (PRIV_CTL_EXTERNAL_LOCK_TEST, EXTERNAL_LOCK_TEST_INIT); if (err) fail ("init lock failed at %d: %s", line, gpg_strerror (err)); } static void external_lock_test_lock (int line) { gpg_error_t err; err = gcry_control (PRIV_CTL_EXTERNAL_LOCK_TEST, EXTERNAL_LOCK_TEST_LOCK); if (err) fail ("taking lock failed at %d: %s", line, gpg_strerror (err)); } static void external_lock_test_unlock (int line) { gpg_error_t err; err = gcry_control (PRIV_CTL_EXTERNAL_LOCK_TEST, EXTERNAL_LOCK_TEST_UNLOCK); if (err) fail ("releasing lock failed at %d: %s", line, gpg_strerror (err)); } static void external_lock_test_destroy (int line) { gpg_error_t err; err = gcry_control (PRIV_CTL_EXTERNAL_LOCK_TEST, EXTERNAL_LOCK_TEST_DESTROY); if (err) fail ("destroying lock failed at %d: %s", line, gpg_strerror (err)); } /* The nonce thread. We simply request a couple of nonces and return. */ static THREAD_RET_TYPE nonce_thread (void *argarg) { struct thread_arg_s *arg = argarg; int i; char nonce[NONCE_SIZE]; for (i = 0; i < N_NONCE_ITERATIONS; i++) { gcry_create_nonce (nonce, sizeof nonce); if (i && !(i%100)) info ("thread %d created %d nonces so far", arg->no, i); } gcry_free (arg); return THREAD_RET_VALUE; } /* To check our locking function we run several threads all accessing the nonce functions. If this function returns we know that there are no obvious deadlocks or failed lock initialization. */ static void check_nonce_lock (void) { struct thread_arg_s *arg; #ifdef _WIN32 HANDLE threads[N_NONCE_THREADS]; int i; int rc; for (i=0; i < N_NONCE_THREADS; i++) { arg = gcry_xmalloc (sizeof *arg); arg->no = i; threads[i] = CreateThread (NULL, 0, nonce_thread, arg, 0, NULL); if (!threads[i]) die ("error creating nonce thread %d: rc=%d", i, (int)GetLastError ()); } for (i=0; i < N_NONCE_THREADS; i++) { rc = WaitForSingleObject (threads[i], INFINITE); if (rc == WAIT_OBJECT_0) info ("nonce thread %d has terminated", i); else fail ("waiting for nonce thread %d failed: %d", i, (int)GetLastError ()); CloseHandle (threads[i]); } #elif HAVE_PTHREAD pthread_t threads[N_NONCE_THREADS]; int rc, i; for (i=0; i < N_NONCE_THREADS; i++) { arg = gcry_xmalloc (sizeof *arg); arg->no = i; pthread_create (&threads[i], NULL, nonce_thread, arg); } for (i=0; i < N_NONCE_THREADS; i++) { rc = pthread_join (threads[i], NULL); if (rc) fail ("pthread_join failed for nonce thread %d: %s", i, strerror (errno)); else info ("nonce thread %d has terminated", i); } #endif /*!_WIN32*/ } -/* Initialze all accounts. */ +/* Initialize all accounts. */ static void init_accounts (void) { int i; for (i=0; i < N_ACCOUNT; i++) account[i] = ACCOUNT_VALUE; } /* Check that the sum of all accounts matches the initial sum. */ static void check_accounts (void) { int i, sum; sum = 0; for (i = 0; i < N_ACCOUNT; i++) sum += account[i]; if (sum != N_ACCOUNT * ACCOUNT_VALUE) die ("accounts out of balance"); } static void print_accounts (void) { int i; for (i=0; i < N_ACCOUNT; i++) printf ("account %d: %6d\n", i, account[i]); } /* Get a a random integer value in the range 0 to HIGH. */ static unsigned int get_rand (int high) { return (unsigned int)(1+(int)((double)(high+1)*rand ()/(RAND_MAX+1.0))) - 1; } /* Pick a random account. Note that this function is not thread-safe. */ static int pick_account (void) { return get_rand (N_ACCOUNT - 1); } /* Pick a random value for a transaction. This is not thread-safe. */ static int pick_value (void) { return get_rand (MAX_TRANSACTION_VALUE); } /* This is the revision department. */ static THREAD_RET_TYPE revision_thread (void *arg) { (void)arg; while (!stop_revision_thread) { external_lock_test_lock (__LINE__); check_accounts (); external_lock_test_unlock (__LINE__); } return THREAD_RET_VALUE; } /* This is one of our accountants. */ static THREAD_RET_TYPE accountant_thread (void *arg) { int i; int acc1, acc2; int value; (void)arg; for (i = 0; i < N_TRANSACTIONS; i++) { external_lock_test_lock (__LINE__); acc1 = pick_account (); acc2 = pick_account (); value = pick_value (); account[acc1] += value; account[acc2] -= value; external_lock_test_unlock (__LINE__); } return THREAD_RET_VALUE; } static void run_test (void) { #ifdef _WIN32 HANDLE rthread; HANDLE athreads[N_ACCOUNTANTS]; int i; int rc; external_lock_test_init (__LINE__); stop_revision_thread = 0; rthread = CreateThread (NULL, 0, revision_thread, NULL, 0, NULL); if (!rthread) die ("error creating revision thread: rc=%d", (int)GetLastError ()); for (i=0; i < N_ACCOUNTANTS; i++) { athreads[i] = CreateThread (NULL, 0, accountant_thread, NULL, 0, NULL); if (!athreads[i]) die ("error creating accountant thread %d: rc=%d", i, (int)GetLastError ()); } for (i=0; i < N_ACCOUNTANTS; i++) { rc = WaitForSingleObject (athreads[i], INFINITE); if (rc == WAIT_OBJECT_0) info ("accountant thread %d has terminated", i); else fail ("waiting for accountant thread %d failed: %d", i, (int)GetLastError ()); CloseHandle (athreads[i]); } stop_revision_thread = 1; rc = WaitForSingleObject (rthread, INFINITE); if (rc == WAIT_OBJECT_0) info ("revision thread has terminated"); else fail ("waiting for revision thread failed: %d", (int)GetLastError ()); CloseHandle (rthread); #else /*!_WIN32*/ pthread_t rthread; pthread_t athreads[N_ACCOUNTANTS]; int rc, i; external_lock_test_init (__LINE__); stop_revision_thread = 0; pthread_create (&rthread, NULL, revision_thread, NULL); for (i=0; i < N_ACCOUNTANTS; i++) pthread_create (&athreads[i], NULL, accountant_thread, NULL); for (i=0; i < N_ACCOUNTANTS; i++) { rc = pthread_join (athreads[i], NULL); if (rc) fail ("pthread_join failed for accountant thread %d: %s", i, strerror (errno)); else info ("accountant thread %d has terminated", i); } stop_revision_thread = 1; rc = pthread_join (rthread, NULL); if (rc) fail ("pthread_join failed for the revision thread: %s", strerror (errno)); else info ("revision thread has terminated"); #endif /*!_WIN32*/ external_lock_test_destroy (__LINE__); } int main (int argc, char **argv) { int last_argc = -1; if (argc) { argc--; argv++; } while (argc && last_argc != argc ) { last_argc = argc; if (!strcmp (*argv, "--help")) { puts ( "usage: ./t-lock [options]\n" "\n" "Options:\n" " --verbose Show what is going on\n" " --debug Flyswatter\n" ); exit (0); } if (!strcmp (*argv, "--verbose")) { verbose = 1; argc--; argv++; } else if (!strcmp (*argv, "--debug")) { verbose = debug = 1; argc--; argv++; } } srand (time(NULL)*getpid()); if (debug) xgcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1u, 0); xgcry_control (GCRYCTL_DISABLE_SECMEM, 0); if (!gcry_check_version (GCRYPT_VERSION)) die ("version mismatch"); /* We are using non-public interfaces - check the exact version. */ if (strcmp (gcry_check_version (NULL), GCRYPT_VERSION)) die ("exact version match failed"); xgcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); xgcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); check_nonce_lock (); init_accounts (); check_accounts (); run_test (); check_accounts (); /* Run a second time to check deinit code. */ run_test (); check_accounts (); if (verbose) print_accounts (); return error_count ? 1 : 0; }