home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / crypl200.zip / CRYPT.H < prev    next >
Text File  |  1996-10-11  |  30KB  |  743 lines

  1. /****************************************************************************
  2. *                                                                            *
  3. *                      cryptlib Internal General Header File                 *
  4. *                        Copyright Peter Gutmann 1992-1996                    *
  5. *                                                                            *
  6. ****************************************************************************/
  7.  
  8. #ifndef _CRYPT_DEFINED
  9.  
  10. #define _CRYPT_DEFINED
  11.  
  12. /* Various compilers handle includes in subdirectories differently.  Most
  13.    will work with paths from a root directory.  Macintoshes don't recognise
  14.    '/'s as path delimiters, but work around it by scanning all 
  15.    subdirectories and treating the files as if they were in the same
  16.    directory (INC_ALL).  Microsoft C, in a braindamaged exception to all
  17.    other compilers, treats the subdirectory as the root (INC_CHILD) */
  18.  
  19. #if ( defined( __MWERKS__ ) || defined( SYMANTEC_C ) ) && !defined( INC_ALL )
  20.   #error You need to predefine INC_ALL in your project file
  21. #elif defined( _MSC_VER ) && !defined( INC_CHILD )
  22.   #error You need to predefine INC_CHILD in your project/make file
  23. #endif /* Checks for various compiler/OS-dependant include paths */
  24.  
  25. /* If the global crypt API header hasn't been included yet, include it now */
  26.  
  27. #ifndef _CAPI_DEFINED
  28.   #include "capi.h"
  29. #endif /* _CAPI_DEFINED */
  30.  
  31. /* If the BigNum header hasn't been included yet, include it now.  This is a
  32.    bit of a waste since it isn't used in most files, but we need it to
  33.    declare various members of the encryption context structure */
  34.  
  35. #ifndef BN_H
  36.   #if defined( INC_ALL )
  37.     #include "bn.h"
  38.   #else
  39.     #include "bnlib/bn.h"
  40.   #endif /* Compiler-specific includes */
  41. #endif /* BN_H */
  42.  
  43. /****************************************************************************
  44. *                                                                            *
  45. *                                OS-Specific Defines                            *
  46. *                                                                            *
  47. ****************************************************************************/
  48.  
  49. /* Try and figure out if we're running under Windows and/or Win32.  We have
  50.    to jump through all sorts of hoops later on, not helped by the fact that
  51.    the method of detecting Windows at compile time changes with different
  52.    versions of Visual C (it's different for each of VC 2.0, 2.1, 4.0, and
  53.    4.1.  They probably change it again in 4.2 but I don't have a copy to
  54.    test) */
  55.  
  56. #if !defined( __WINDOWS__ ) && ( defined( _Windows ) || defined( _WINDOWS ) )
  57.   #define __WINDOWS__
  58. #endif /* !__WINDOWS__ && ( _Windows || _WINDOWS ) */
  59. #if !defined( __WIN32__ ) && ( defined( WIN32 ) || defined( _WIN32 ) )
  60.   #ifndef __WINDOWS__
  61.     #define __WINDOWS__
  62.   #endif /* __WINDOWS__ */
  63.   #define __WIN32__
  64. #endif /* !__WIN32__ && ( WIN32 || _WIN32 ) */
  65. #if defined( __WINDOWS__ ) && !defined( __WIN32__ )
  66.   #define __WIN16__
  67. #endif /* __WINDOWS__ && !__WIN32__ */
  68.  
  69. /* Fix up a type clash with a Windows predefined type - for some reason BYTE
  70.    and WORD are unsigned, but LONG is signed (actually DWORD is the Windows
  71.    unsigned type, the counterpoint CHAR, SHORT and LONG types are all signed,
  72.    but DWORD is a Windows-ism which all the Unix types will LART me for if I
  73.    start using it) */
  74.  
  75. #if defined( __WINDOWS__ )
  76.   #undef LONG
  77. #endif /* __WINDOWS__ */
  78.  
  79. /* Some encryption algorithms which rely on longints having 32 bits won't
  80.    work on 64- or 128-bit machines due to problems with sign extension and
  81.    whatnot.  The following define can be used to enable special handling for
  82.    processors with a > 32 bit word size */
  83.  
  84. #include <limits.h>
  85. #if ULONG_MAX > 0xFFFFFFFFUL
  86.   #define _BIG_WORDS
  87. #endif /* LONG > 32 bits */
  88.  
  89. /* Some useful types.  We have to jump through all sorts of hoops for
  90.    Windoze */
  91.  
  92. #ifndef __WIN32__
  93.   typedef int                BOOLEAN;
  94. #endif /* __WIN32__ */
  95. typedef unsigned char        BYTE;
  96. #if !defined( __WINDOWS__ ) || defined( __WIN32__ )
  97.   typedef unsigned short    WORD;
  98. #endif /* !__WINDOWS__ || __WIN32__ */
  99. #ifdef __WIN32__
  100.   #pragma warning( disable : 4142 )
  101.   typedef unsigned long        LONG;
  102.   #pragma warning( default : 4142 )
  103.   #ifdef _WIN32
  104.     /* Visual C 2.1+ doesn't seem to like LONG being typedef'd to unsigned
  105.        no matter what you do, so we rely on the preprocessor to get rid of
  106.        the problem.  Visual C 2.1+ defined _WIN32 whereas 2.0 defined WIN32,
  107.        so we can use this to tell the two apart */
  108.     #define LONG    unsigned long
  109.   #endif /* _WIN32 */
  110. #else
  111.   typedef unsigned long        LONG;
  112. #endif  /* __WIN32__ */
  113.  
  114. /* Boolean constants */
  115.  
  116. #ifndef TRUE
  117.   #define FALSE            0
  118.   #define TRUE            !FALSE
  119. #endif /* TRUE */
  120.  
  121. /* If the endianness is not defined and the compiler can tell us what
  122.    endianness we've got, use this in preference to all other methods.  This
  123.    is only really necessary on non-Unix systems since the makefile kludge
  124.    will tell us the endianness under Unix */
  125.  
  126. #if !defined( LITTLE_ENDIAN ) && !defined( BIG_ENDIAN )
  127.   #if defined( _M_I86 ) || defined( _M_IX86 ) || defined( __TURBOC__ )
  128.     #define LITTLE_ENDIAN        /* Intel architecture always little-endian */
  129.   #elif defined( AMIGA ) || defined( __MWERKS__ ) || defined( SYMANTEC_C )
  130.     #define BIG_ENDIAN            /* Motorola architecture always big-endian */
  131.   #elif defined( VMS ) || defined( __VMS )
  132.     #define LITTLE_ENDIAN        /* VAX architecture always little-endian */
  133.   #elif defined __GNUC__
  134.     #ifdef BYTES_BIG_ENDIAN
  135.       #define BIG_ENDIAN        /* Big-endian byte order */
  136.     #else
  137.       #define LITTLE_ENDIAN        /* Undefined = little-endian byte order */
  138.     #endif /* __GNUC__ */
  139.   #endif /* Compiler-specific endianness checks */
  140. #endif /* !( LITTLE_ENDIAN || BIG_ENDIAN ) */
  141.  
  142. /* The last-resort method.  Thanks to Shawn Clifford
  143.    <sysop@robot.nuceng.ufl.edu> for this trick.
  144.  
  145.    NB: A number of compilers aren't tough enough for this test */
  146.  
  147. #if !defined( LITTLE_ENDIAN ) && !defined( BIG_ENDIAN )
  148.   #if ( ( ( unsigned short ) ( 'AB' ) >> 8 ) == 'B' )
  149.     #define LITTLE_ENDIAN
  150.   #elif ( ( ( unsigned short ) ( 'AB' ) >> 8 ) == 'A' )
  151.     #define BIG_ENDIAN
  152.   #else
  153.     #error Cannot determine processor endianness - edit crypt.h and recompile
  154.   #endif /* Endianness test */
  155. #endif /* !( LITTLE_ENDIAN || BIG_ENDIAN ) */
  156.  
  157. /* Some systems define both BIG_ENDIAN and LITTLE_ENDIAN, then define
  158.    BYTE_ORDER to the appropriate one, so we check this and undefine the
  159.    appropriate one */
  160.  
  161. #if defined( BIG_ENDIAN ) && defined( LITTLE_ENDIAN )
  162.   #ifdef BYTE_ORDER
  163.     #if BYTE_ORDER == BIG_ENDIAN
  164.       #undef LITTLE_ENDIAN
  165.     #else
  166.       #undef BIG_ENDIAN
  167.     #endif /* BYTE_ORDER-specific undef */
  168.   #else
  169.     #error Both LITTLE_ENDIAN and BIG_ENDIAN are defined in crypt.h - edit the settings and recompile
  170.   #endif /* BYTE_ORDER */
  171. #endif /* LITTLE_ENDIAN && BIG_ENDIAN */
  172.  
  173. /* Some C routines can be replaced with faster assembly-language equivalents
  174.    for some systems.  These should really be defined in a makefile, but
  175.    smegging Visual C will silently truncate all command-line defines when
  176.    the line goes over 127 characters, so we define them here instead and
  177.    save the makefile command line for other things */
  178.  
  179. #if defined( __MSDOS__ ) || defined( __WIN16__ )
  180.   #define ASM_SAFER
  181. #endif /* __MSDOS__ || __WIN16__ */
  182.  
  183. /****************************************************************************
  184. *                                                                            *
  185. *                                Portability Defines                            *
  186. *                                                                            *
  187. ****************************************************************************/
  188.  
  189. /* If we're running on a 64-bit CPU we often need to mask values off to 32
  190.    bits.  The following define enables this if the CPU word size is
  191.    > 64 bits */
  192.  
  193. #ifdef _BIG_WORDS
  194.   #define MASK32( x )    ( ( x ) & 0xFFFFFFFFUL )
  195. #else
  196.   #define MASK32( x )    x
  197. #endif /* _BIG_WORDS */
  198.  
  199. /* The odd algorithm needs masking to 16 bits */
  200.  
  201. #if UINT_MAX > 0xFFFFUL
  202.   #define MASK16( x )    ( ( x ) & 0xFFFFUL )
  203. #else
  204.   #define MASK16( x )    x
  205. #endif /* > 16-bit ints */
  206.  
  207. /* If we're running on a machine with > 32 bit wordsize we need to jump
  208.    through all sorts of hoops to convert data from arrays of bytes to arrays
  209.    of longints.  The following macros pull bytes out of memory and assemble
  210.    them into a longword, and deposit a longword into memory as a series of
  211.    bytes.  This code really blows on any processors which need to use it */
  212.  
  213. #ifdef BIG_ENDIAN
  214.     #define mgetLong(memPtr)        \
  215.         ( ( ( LONG ) memPtr[ 0 ] << 24 ) | ( ( LONG ) memPtr[ 1 ] << 16 ) | \
  216.           ( ( LONG ) memPtr[ 2 ] << 8 ) | ( ( LONG ) memPtr[ 3 ] ) ); \
  217.         memPtr += 4
  218.  
  219.     #define mputLong(memPtr,data)    \
  220.         memPtr[ 0 ] = ( BYTE ) ( ( ( data ) >> 24 ) & 0xFF ); \
  221.         memPtr[ 1 ] = ( BYTE ) ( ( ( data ) >> 16 ) & 0xFF ); \
  222.         memPtr[ 2 ] = ( BYTE ) ( ( ( data ) >> 8 ) & 0xFF ); \
  223.         memPtr[ 3 ] = ( BYTE ) ( ( data ) & 0xFF ); \
  224.         memPtr += 4
  225. #else
  226.     #define mgetLong(memPtr)        \
  227.         ( ( ( LONG ) memPtr[ 0 ] ) | ( ( LONG ) memPtr[ 1 ] << 8 ) | \
  228.           ( ( LONG ) memPtr[ 2 ] << 16 ) | ( ( LONG ) memPtr[ 3 ] << 24 ) ); \
  229.         memPtr += 4
  230.  
  231.     #define mputLong(memPtr,data)    \
  232.         memPtr[ 0 ] = ( BYTE ) ( ( data ) & 0xFF ); \
  233.         memPtr[ 1 ] = ( BYTE ) ( ( ( data ) >> 8 ) & 0xFF ); \
  234.         memPtr[ 2 ] = ( BYTE ) ( ( ( data ) >> 16 ) & 0xFF ); \
  235.         memPtr[ 3 ] = ( BYTE ) ( ( ( data ) >> 24 ) & 0xFF ); \
  236.         memPtr += 4
  237. #endif /* BIG_ENDIAN */
  238.  
  239. /* Copy an array of bytes to an array of 32-bit words.  We need to take
  240.    special precautions when the machine word size is > 32 bits because we
  241.    can't just assume BYTE[] == LONG[] */
  242.  
  243. #ifdef _BIG_WORDS
  244.   #define copyToLong(dest,src,count)    \
  245.                     { \
  246.                     LONG *destPtr = ( LONG * ) dest; \
  247.                     BYTE *srcPtr = src; \
  248.                     int i; \
  249.                     for( i = 0; i < count / 4; i++ ) \
  250.                         { \
  251.                         destPtr[ i ] = mgetLong( srcPtr ); \
  252.                         } \
  253.                     }
  254. #else
  255.   #define copyToLong(dest,src,count) \
  256.                     memcpy( dest, src, count )
  257. #endif /* _BIG_WORDS */
  258.  
  259. /* Versions of the above which are guaranteed to always be big or
  260.    little-endian (these are needed for some algorithms where the external
  261.    data format is always little-endian, eg anything designed by Ron
  262.    Rivest) */
  263.  
  264. #define mgetBWord(memPtr)        \
  265.         ( ( WORD ) memPtr[ 0 ] << 0 ) | ( ( WORD ) memPtr[ 1 ] ); \
  266.         memPtr += 2
  267.  
  268. #define mputBWord(memPtr,data)    \
  269.         memPtr[ 0 ] = ( BYTE ) ( ( ( data ) >> 8 ) & 0xFF ); \
  270.         memPtr[ 1 ] = ( BYTE ) ( ( data ) & 0xFF ); \
  271.         memPtr += 2
  272.  
  273. #define mgetBLong(memPtr)        \
  274.         ( ( ( LONG ) memPtr[ 0 ] << 24 ) | ( ( LONG ) memPtr[ 1 ] << 16 ) | \
  275.           ( ( LONG ) memPtr[ 2 ] << 8 ) | ( LONG ) memPtr[ 3 ] ); \
  276.         memPtr += 4
  277.  
  278. #define mputBLong(memPtr,data)    \
  279.         memPtr[ 0 ] = ( BYTE ) ( ( ( data ) >> 24 ) & 0xFF ); \
  280.         memPtr[ 1 ] = ( BYTE ) ( ( ( data ) >> 16 ) & 0xFF ); \
  281.         memPtr[ 2 ] = ( BYTE ) ( ( ( data ) >> 8 ) & 0xFF ); \
  282.         memPtr[ 3 ] = ( BYTE ) ( ( data ) & 0xFF ); \
  283.         memPtr += 4
  284.  
  285. #define mgetLWord(memPtr)        \
  286.         ( ( WORD ) memPtr[ 0 ] ) | ( ( WORD ) memPtr[ 1 ] << 8 ); \
  287.         memPtr += 2
  288.  
  289. #define mputLWord(memPtr,data)    \
  290.         memPtr[ 0 ] = ( BYTE ) ( ( data ) & 0xFF ); \
  291.         memPtr[ 1 ] = ( BYTE ) ( ( ( data ) >> 8 ) & 0xFF ); \
  292.         memPtr += 2
  293.  
  294. #define mgetLLong(memPtr)        \
  295.         ( ( ( LONG ) memPtr[ 0 ] ) | ( ( LONG ) memPtr[ 1 ] << 8 ) | \
  296.           ( ( LONG ) memPtr[ 2 ] << 16 ) | ( ( LONG ) memPtr[ 3 ] << 24 ) ); \
  297.         memPtr += 4
  298.  
  299. #define mputLLong(memPtr,data)    \
  300.         memPtr[ 0 ] = ( BYTE ) ( ( data ) & 0xFF ); \
  301.         memPtr[ 1 ] = ( BYTE ) ( ( ( data ) >> 8 ) & 0xFF ); \
  302.         memPtr[ 2 ] = ( BYTE ) ( ( ( data ) >> 16 ) & 0xFF ); \
  303.         memPtr[ 3 ] = ( BYTE ) ( ( ( data ) >> 24 ) & 0xFF ); \
  304.         memPtr += 4
  305.  
  306. #ifdef _BIG_WORDS
  307.   #define copyToLLong(dest,src,count)    \
  308.                     { \
  309.                     LONG *destPtr = ( LONG * ) dest; \
  310.                     BYTE *srcPtr = src; \
  311.                     int i; \
  312.                     for( i = 0; i < count / 4; i++ ) \
  313.                         { \
  314.                         destPtr[ i ] = mgetLLong( srcPtr ); \
  315.                         } \
  316.                     }
  317.  
  318.   #define copyToBLong(dest,src,count)    \
  319.                     { \
  320.                     LONG *destPtr = ( LONG * ) dest; \
  321.                     BYTE *srcPtr = src; \
  322.                     int i; \
  323.                     for( i = 0; i < count / 4; i++ ) \
  324.                         { \
  325.                         destPtr[ i ] = mgetBLong( srcPtr ); \
  326.                         } \
  327.                     }
  328. #endif /* _BIG_WORDS */
  329.  
  330. /* Functions to convert the endianness from the canonical form to the
  331.    internal form.  bigToLittle() convert from big-endian in-memory to
  332.    little-endian in-CPU, littleToBig() convert from little-endian in-memory
  333.    to big-endian in-CPU */
  334.  
  335. void longReverse( LONG *buffer, int count );
  336. void wordReverse( WORD *buffer, int count );
  337.  
  338. #ifdef LITTLE_ENDIAN
  339.   #define bigToLittleLong( x, y )    longReverse(x,y)
  340.   #define bigToLittleWord( x, y )    wordReverse(x,y)
  341.   #define littleToBigLong( x, y )
  342.   #define littleToBigWord( x, y )
  343. #else
  344.   #define bigToLittleLong( x, y )
  345.   #define bigToLittleWord( x, y )
  346.   #define littleToBigLong( x, y )    longReverse(x,y)
  347.   #define littleToBigWord( x, y )    wordReverse(x,y)
  348. #endif /* LITTLE_ENDIAN */
  349.  
  350. /****************************************************************************
  351. *                                                                            *
  352. *                                Data Structures                                *
  353. *                                                                            *
  354. ****************************************************************************/
  355.  
  356. /* The size of the key cookie for session keys and signature cookie for
  357.    signed data */
  358.  
  359. #define KEY_COOKIE_SIZE            4
  360. #define SIGNATURE_COOKIE_SIZE    8
  361.  
  362. #define MAX_COOKIE_SIZE            SIGNATURE_COOKIE_SIZE
  363.  
  364. /* The maximum possible IV size.  Although CRYPT_MAX_IVSIZE is standardised
  365.    at 64 bits to hide the details of the algorithm being used when the
  366.    algorithm is decided via a high-level function, some algorithms have
  367.    larger block sizes which require more than 64 bits of IV.  The MAX_IVSIZE
  368.    define is provided to declare storage space for these internal IV's */
  369.  
  370. #define MAX_IVSIZE            32
  371.  
  372. /* The quantization level for KeyInfo records.  Records which are visible
  373.    to outsiders are padded out to a multiple of this size to obscure the
  374.    nature of their contents */
  375.  
  376. #define KEYINFO_PADSIZE        64
  377.  
  378. /* Declare a BigNum type to save having to use `struct BigNum' all over the
  379.    place */
  380.  
  381. typedef struct BigNum    BIGNUM;
  382.  
  383. /* A forward declaration for the parameter type passed to functions in the
  384.    CAPABILITY_INFO struct */
  385.  
  386. struct CI;
  387.  
  388. /* The structure used to store internal information about the crypto library
  389.    capabilities.  This information is used internally by the library and is
  390.    not available to users */
  391.  
  392. typedef struct CA {
  393.     /* Basic identification information for the algorithm */
  394.     CRYPT_ALGO cryptAlgo;            /* The encryption algorithm */
  395.     CRYPT_MODE cryptMode;            /* The encryption mode */
  396.     int blockSize;                    /* The basic block size of the algorithm */
  397.     char *algoName;                    /* Algorithm name */
  398.     char *modeName;                    /* Mode name */
  399.     int speed;                        /* Speed relative to block copy */
  400.  
  401.     /* Keying information.  Note that the maximum sizes may vary (for
  402.        example for two-key triple DES vs three-key triple DES) so the
  403.        crypt query functions should be used to determine the actual size
  404.        for a particular context rather than just using maxKeySize */
  405.     int minKeySize;                    /* Minimum key size in bytes */
  406.     int keySize;                    /* Recommended key size in bytes */
  407.     int maxKeySize;                    /* Maximum key size in bytes */
  408.  
  409.     /* IV information */
  410.     int minIVsize;                    /* Minimum IV size in bytes */
  411.     int ivSize;                        /* Recommended IV size in bytes */
  412.     int maxIVsize;                    /* Maximum IV size in bytes */
  413.  
  414.     /* The functions for implementing the algorithm */
  415.     int ( *selfTestFunction )( void );
  416.     int ( *initFunction )( struct CI CPTR cryptInfo );
  417.     int ( *initExFunction )( struct CI CPTR cryptInfo, const void CPTR cryptInfoEx );
  418.     int ( *endFunction )( struct CI CPTR cryptInfo );
  419.     int ( *initKeyFunction )( struct CI CPTR cryptInfo );
  420.     int ( *initIVFunction )( struct CI CPTR cryptInfo );
  421.     int ( *getKeysizeFunction )( struct CI CPTR cryptInfo );
  422.     int ( *getDataFunction )( struct CI CPTR cryptInfo, void CPTR buffer );
  423.     int ( *encryptFunction )( struct CI CPTR cryptInfo, void CPTR buffer, int length );
  424.     int ( *decryptFunction )( struct CI CPTR cryptInfo, void CPTR buffer, int length );
  425.  
  426.     /* The results of the self-test for this algorithm */
  427.     int selfTestStatus;
  428.  
  429.     /* The next record in the list */
  430.     struct CA *next;                /* Pointer to the next record */
  431.     } CAPABILITY_INFO;
  432.  
  433. /* An encryption context.  Note the order of the BYTE[] fields in this
  434.    structure, which ensures they're aligned to the machine word size */
  435.  
  436. typedef struct CI {
  437.     /* Whether this is a conventional or PKC context */
  438.     BOOLEAN isPKCcontext;            /* Whether this is a PKC context */
  439.  
  440.     /* Basic information on the encryption we're using */
  441.     CAPABILITY_INFO *capabilityInfo;/* The encryption capability data */
  442.  
  443.     /* User keying information.  The user key is the key as entered by the
  444.        user, the IV is the initial IV stored in canonical form */
  445.     BYTE userKey[ CRYPT_MAX_KEYSIZE ];        /* User encryption key */
  446.     BYTE iv[ CRYPT_MAX_IVSIZE ];    /* Initial IV */
  447.     int userKeyLength;                /* User encryption key length in bytes */
  448.     int ivLength;                    /* IV length in bytes */
  449.     BOOLEAN keySet;                    /* Whether the key is set up */
  450.     BOOLEAN ivSet;                    /* Whether the IV is set up */
  451.  
  452.     /* Control information for the key.  The key control vector is applied
  453.        in the standard IBM-designed way, and may also be used to control
  454.        hardware-based encryption systems.  The key cookie is the first
  455.        KEY_COOKIE_SIZE bytes of the hash of the DER-encoded key information
  456.        record */
  457.     long controlVector;                /* User key control vector */
  458.     BYTE keyCookie[ KEY_COOKIE_SIZE ];    /* Key cookie for this algo/mode/key */
  459.     int exportKeyCookie;            /* Whether to export the key cookie */
  460.  
  461.     /* Information obtained when a key suitable for use by this algorithm
  462.        is derived from a longer user key */
  463.     int keySetupIterations;            /* Number of times setup was iterated */
  464.     CRYPT_ALGO keySetupAlgorithm;    /* Algorithm used for key setup */
  465.  
  466.     /* Conventional encryption keying information.  The key is the raw
  467.        encryption key stored in whatever form is required by the algorithm.
  468.        This may be simply an endianness-adjusted form of the transformed key
  469.        (in the case of algorithms like MDC/SHS) or a processed form of the
  470.        user key (in the case of algorithms like DES or IDEA).  The IV is the
  471.        current working IV stored in an endianness-adjusted form.  The ivCount
  472.        is the number of bytes of IV in use, and may be used for various
  473.        chaining modes.  These fields may be unused if the algorithm is
  474.        implemented in hardware */
  475.     void *key;                        /* Internal working key */
  476.     BYTE currentIV[ MAX_IVSIZE ];    /* Internal working IV */
  477.     int keyLength;                    /* Internal key length in bytes */
  478.     int ivCount;                    /* Internal IV count for chaining modes */
  479.  
  480.     /* Public-key encryption keying information.  The key component pointer
  481.        is a generic pointer to the structure containing the various PKC key
  482.        components.  The BigNums are the key components which are loaded from
  483.        the key component pointer when loadCryptContext() is called.  Since
  484.        each algorithm has its own unique parameters, they are given generic
  485.        names here.  The actual algorithm implementations refer to them by
  486.        their actual names, which are implemented as symbolic defines of the
  487.        form <algo>Param_<param_name>, eg rsaParam_e */
  488.     void *keyComponentPtr;            /* Key components in external form */
  489.     BOOLEAN keyComponentsLittleEndian;    /* Whether key components are l/e */
  490.     BOOLEAN isPublicKey;            /* Whether key is a public key */
  491.     int keySizeBits;                /* Nominal key size in bits */
  492.     BIGNUM pkcParam1;
  493.     BIGNUM pkcParam2;
  494.     BIGNUM pkcParam3;
  495.     BIGNUM pkcParam4;
  496.     BIGNUM pkcParam5;
  497.     BIGNUM pkcParam6;
  498.     BIGNUM pkcParam7;
  499.     BIGNUM pkcParam8;                /* The PKC key components */
  500.     BYTE keyID[ CRYPT_MAX_KEYIDSIZE ];    /* Encoded key ID for this key */
  501.     int keyIDlength;                /* Length of key ID data */
  502.     int exportSigCookie;            /* Whether to export the sig.cookie */
  503.     BYTE sigCookie[ SIGNATURE_COOKIE_SIZE ];    /* Sig.cookie for this sig.*/
  504.     BOOLEAN useOAEP;                /* Whether to use Bellare-Rogaway
  505.                                        optimal asymmetric encryption padding */
  506.     char *userID;                    /* User ID for this key when stored
  507.                                        externally */
  508.  
  509.     /* Once the key components are stored in the internal form, retrieving
  510.        them from the algorithm-dependant BigNum storage is somewhat complex,
  511.        so we keep a copy of the components in the original external form
  512.        alongside the data in BigNum form.  The following field is used as a
  513.        pointer to the appropriate CRYPT_PKCINFO_xxx structure */
  514.     void *pkcInfo;
  515.  
  516.     /* Private data needed by the algorithm.  We also keep track of whether
  517.        we're using default values for the private data settings */
  518.     void *privateData;                /* For private use */
  519.     BOOLEAN privateUseDefaults;        /* Whether priv.data vals.are defaults */
  520.  
  521.     /* Some of the high-level library routines call the lower-level ones with
  522.        preformatted data to process in the buffer passed to the routine.  If
  523.        this is sensitive, it should be cleared as soon as it is no longer
  524.        used.  However if the lower-level routine is called directly by the
  525.        user, the input buffer shouldn't be modified.  The following flag
  526.        determines whether the buffer should be cleared.  The use of this flag
  527.        isn't necessary for the PKC functions which always clear the buffer
  528.        while the data in it is stored in a bignum */
  529.     BOOLEAN clearBuffer;
  530.  
  531.     /* A check value so we can determine whether the crypt context has been
  532.        initialised or not.  This is needed because passing in an
  533.        uninitialised block of memory as a crypt context can lead to problems
  534.        when we try to dereference wild pointers */
  535.     LONG checkValue;
  536.  
  537.     /* The next and previous encryption context in the linked list of
  538.        contexts */
  539.     struct CI *next, *prev;
  540.     } CRYPT_INFO;
  541.  
  542. /* Symbolic defines for the various PKC components for different PKC
  543.    algorithms */
  544.  
  545. #define rsaParam_n            pkcParam1
  546. #define rsaParam_e            pkcParam2
  547. #define rsaParam_d            pkcParam3
  548. #define rsaParam_p            pkcParam4
  549. #define rsaParam_q            pkcParam5
  550. #define rsaParam_u            pkcParam6
  551. #define rsaParam_exponent1    pkcParam7
  552. #define rsaParam_exponent2    pkcParam8
  553.  
  554. #define dsaParam_p            pkcParam1
  555. #define dsaParam_q            pkcParam2
  556. #define dsaParam_g            pkcParam3
  557. #define dsaParam_x            pkcParam4
  558. #define dsaParam_y            pkcParam5
  559.  
  560. #define dhParam_p            pkcParam1
  561. #define dhParam_g            pkcParam2
  562. #define dhParam_x            pkcParam3
  563. #define dhParam_y            pkcParam4
  564.  
  565. /* Because there's no really clean way to throw an exception in C and the
  566.    bnlib routines don't carry around state information like the stream
  567.    library does, we need to perform an error check for most of the routines
  568.    we call.  To make this slightly less ugly we define the following macro
  569.    which performs the check for us by updating a variable called `status'
  570.    with the result of a bnlib call */
  571.  
  572. #define CK( x )    status |= x
  573.  
  574. /****************************************************************************
  575. *                                                                            *
  576. *                                Internal API Functions                        *
  577. *                                                                            *
  578. ****************************************************************************/
  579.  
  580. /* Reasonably reliable way to get rid of unused argument warnings in a
  581.    compiler-independant manner */
  582.  
  583. #define UNUSED( arg )    ( ( arg ) = ( arg ) )
  584.  
  585. /* Although min() and max() aren't in the ANSI standard, most stdlib.h's have
  586.    them anyway for historical reasons.  Just in case they're not defined
  587.    there by some pedantic compiler (some versions of Borland C do this), we
  588.    define them here */
  589.  
  590. #ifndef max
  591.   #define max( a, b )    ( ( ( a ) > ( b ) ) ? ( a ) : ( b ) )
  592. #endif /* !max */
  593. #ifndef min
  594.   #define min( a, b )    ( ( ( a ) < ( b ) ) ? ( a ) : ( b ) )
  595. #endif /* !min */
  596.  
  597. /* Whether an encryption mode needs an IV or not */
  598.  
  599. #define needsIV( mode )    ( mode == CRYPT_MODE_CBC || \
  600.                           mode == CRYPT_MODE_CFB || \
  601.                           mode == CRYPT_MODE_OFB || \
  602.                           mode == CRYPT_MODE_PCBC )
  603.  
  604. /* Whether an algorithm is a PKC algorithm */
  605.  
  606. #define isPKCalgorithm( algorithm )    \
  607.     ( algorithm >= CRYPT_ALGO_RSA && algorithm <= CRYPT_ALGO_DSS )
  608.  
  609. /* To convert from the external cookies which are used to reference internal
  610.    data structures to the internal structure itself, we subtract an offset
  611.    from the external cookie to obtain a pointer to the internal structure.
  612.    The use of the conversion offset means programs outside the library
  613.    security perimeter will generate a protection violation if they try to
  614.    treat the cookie as a pointer to anything unless they go to some lengths
  615.    to determine the conversion value.  To this end makeCookie() forces an odd
  616.    address which gives an address error on many architectures */
  617.  
  618. extern int cryptContextConversionOffset;
  619.  
  620. #define CONTEXT_TO_INFO( x )    ( CRYPT_INFO * ) ( ( BYTE * ) x - cryptContextConversionOffset )
  621. #define INFO_TO_CONTEXT( x )    ( CRYPT_CONTEXT ) ( ( BYTE * ) x + cryptContextConversionOffset )
  622.  
  623. #define makeCookie( cookie )    ( cookie | 1 )
  624. #define isBadCookie( cookie )    ( cookie == NULL || !( ( int ) ( ( long ) cookie ) & 1 ) )
  625.  
  626. /* A magic value to detect whether an internal structure has been
  627.    initialised yet */
  628.  
  629. #define CRYPT_MAGIC        0xC0EDBABEUL
  630.  
  631. /* The default number of setup iterations and hash algorithm for
  632.    cryptDeriveKey() */
  633.  
  634. #define DEFAULT_KEYSETUP_ITERATIONS    100
  635. #define DEFAULT_KEYSETUP_ALGO        CRYPT_ALGO_SHA
  636.  
  637. /* The precise type of the key file or database we're working with.  This is
  638.    used for type checking to make sure we don't try to find private keys in
  639.    a collection of public-key certificates or whatever */
  640.  
  641. typedef enum {
  642.     KEYSET_SUBTYPE_NONE,            /* Unknown */
  643.     KEYSET_SUBTYPE_ERROR,            /* Bad keyset format */
  644.     KEYSET_SUBTYPE_PUBLIC,            /* Public keys */
  645.     KEYSET_SUBTYPE_PRIVATE            /* Private keys */
  646.     } KEYSET_SUBTYPE;
  647.  
  648. /* Secure and lower-security memory handling functions */
  649.  
  650. int secureMalloc( void **pointer, int size );
  651. void secureFree( void **pointer );
  652. void cleanFree( void **pointer, int count );
  653.  
  654. /* A macro to clear sensitive data from memory.  This is somewhat easier to
  655.    use than calling memset with the second parameter 0 all the time, and
  656.    makes it obvious where sensitive data is being erased */
  657.  
  658. #define zeroise( memory, size )        memset( memory, 0, size )
  659.  
  660. /* Routines to get/set algorithm-specific information.  These should really
  661.    be implemented as capabilityInfo function pointers but this makes type
  662.    checking difficult */
  663.  
  664. BOOLEAN getDESinfo( const CRYPT_INFO *cryptInfo );
  665. void setDESinfo( CRYPT_INFO *cryptInfo, const BOOLEAN isDESX );
  666. BOOLEAN get3DESinfo( const CRYPT_INFO *cryptInfo );
  667. void set3DESinfo( CRYPT_INFO *cryptInfo, const BOOLEAN isThreeKey );
  668. int getMDCSHSinfo( const CRYPT_INFO *cryptInfo );
  669. void setMDCSHSinfo( CRYPT_INFO *cryptInfo, const int keySetupIterations );
  670. int getRC5info( const CRYPT_INFO *cryptInfo );
  671. void setRC5info( CRYPT_INFO *cryptInfo, const int rounds );
  672. int getSaferInfo( const CRYPT_INFO *cryptInfo, BOOLEAN *useSaferSK );
  673. void setSaferInfo( CRYPT_INFO *cryptInfo, const BOOLEAN useSaferSK,
  674.                    const int rounds );
  675. int getBlowfishInfo( const CRYPT_INFO *cryptInfo, BOOLEAN *useBlowfishSK );
  676. void setBlowfishInfo( CRYPT_INFO *cryptInfo, const BOOLEAN useBlowfishSK,
  677.                       const int keySetupIterations );
  678. BOOLEAN getSHAinfo( const CRYPT_INFO *cryptInfo );
  679. void setSHAinfo( CRYPT_INFO *cryptInfo, const BOOLEAN isSHA );
  680.  
  681. /* Random data management routines */
  682.  
  683. int getRandomByte( void );
  684. void endRandom( void );
  685. void getNonce( void *nonce, int nonceLength );
  686.  
  687. /* Key management routines */
  688.  
  689. BOOLEAN matchSubstring( const char *subString, const char *string );
  690. int generateKeyID( CRYPT_ALGO algorithm, BYTE *keyID, int *keyIDlength, \
  691.                    void *pkcInfo );
  692. int generateKeyCookie( CRYPT_INFO *cryptInfo );
  693. int loadIV( CRYPT_INFO *cryptInfo, const BYTE *iv, const int ivLength );
  694.  
  695. /* Key database routines.  These are handled internally by cryptdbx.c since
  696.    the involve manipulation of KEYSET_INFO structures which aren't exported
  697.    to the library as a whole */
  698.  
  699. int setKeysetNames( void *keySet, CRYPT_IOCTLINFO_KEYSETNAMES *ioctlInfo );
  700.  
  701. /* Hash state information.  We can either call the hash function with
  702.    HASH_ALL to process an entire buffer at a time, or HASH_START/
  703.    HASH_CONTINUE/HASH_END to process it in parts */
  704.  
  705. typedef enum { HASH_START, HASH_CONTINUE, HASH_END, HASH_ALL } HASH_STATE;
  706.  
  707. /* The hash functions are used quite a bit by the library so we provide an
  708.    internal API for them to avoid the overhead of having to set up an
  709.    encryption context every time they're needed.  These take a block of
  710.    input data and hash it, leaving the result in the output buffer.  If the
  711.    hashState parameter is HASH_ALL the the hashInfo parameter may be NULL,
  712.    in which case the function will use its own memory for the hashInfo */
  713.  
  714. #define MAX_HASHINFO_SIZE    200
  715.  
  716. typedef void ( *HASHFUNCTION )( void *hashInfo, BYTE *outBuffer, \
  717.                                 BYTE *inBuffer, int length, \
  718.                                 const HASH_STATE hashState );
  719.  
  720. BOOLEAN getHashParameters( const CRYPT_ALGO hashAlgorithm,
  721.                            HASHFUNCTION *hashFunction, int *hashInputSize,
  722.                            int *hashOutputSize, int *hashInfoSize );
  723.  
  724. /* Query library config options.  Note that the return values have to be
  725.    int's rather than BOOLEAN's because they can be CRYPT_USE_DEFAULT as well
  726.    as TRUE or FALSE */
  727.  
  728. void setOptionMemoryLockType( int memoryLockType );
  729. void setOptionExportKeyCookie( const BOOLEAN option );
  730. BOOLEAN getOptionExportKeyCookie( void );
  731. void setOptionExportSigCookie( const BOOLEAN option );
  732. BOOLEAN getOptionExportSigCookie( void );
  733. void setOptionUseOAEP( const BOOLEAN option );
  734. BOOLEAN getOptionUseOAEP( void );
  735. void setOptionKeysetNames( const CRYPT_IOCTLINFO_KEYSETNAMES *keysetNames );
  736. void getOptionKeysetNames( CRYPT_IOCTLINFO_KEYSETNAMES *keysetNames );
  737. int getOptionHashAlgo( void );
  738. int getOptionPKCAlgo( void );
  739. int getOptionCryptAlgo( void );
  740. int getOptionCryptMode( void );
  741.  
  742. #endif /* _CRYPT_DEFINED */
  743.