/*
             Common Public License Version 0.5

             THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF
             THIS COMMON PUBLIC LICENSE ("AGREEMENT"). ANY USE,
             REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES
             RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.

             1. DEFINITIONS

             "Contribution" means: 
                   a) in the case of the initial Contributor, the
                   initial code and documentation distributed under
                   this Agreement, and 

                   b) in the case of each subsequent Contributor:
                   i) changes to the Program, and
                   ii) additions to the Program;

                   where such changes and/or additions to the Program
                   originate from and are distributed by that
                   particular Contributor. A Contribution 'originates'
                   from a Contributor if it was added to the Program
                   by such Contributor itself or anyone acting on such
                   Contributor's behalf. Contributions do not include
                   additions to the Program which: (i) are separate
                   modules of software distributed in conjunction with
                   the Program under their own license agreement, and
                   (ii) are not derivative works of the Program.


             "Contributor" means any person or entity that distributes
             the Program.

             "Licensed Patents " mean patent claims licensable by a
             Contributor which are necessarily infringed by the use or
             sale of its Contribution alone or when combined with the
             Program. 

             "Program" means the Contributions distributed in
             accordance with this Agreement.

             "Recipient" means anyone who receives the Program under
             this Agreement, including all Contributors.

             2. GRANT OF RIGHTS

                   a) Subject to the terms of this Agreement, each
                   Contributor hereby grants Recipient a
                   non-exclusive, worldwide, royalty-free copyright
                   license to reproduce, prepare derivative works of,
                   publicly display, publicly perform, distribute and
                   sublicense the Contribution of such Contributor, if
                   any, and such derivative works, in source code and
                   object code form.

                   b) Subject to the terms of this Agreement, each
                   Contributor hereby grants Recipient a
                   non-exclusive, worldwide, royalty-free patent
                   license under Licensed Patents to make, use, sell,
                   offer to sell, import and otherwise transfer the
                   Contribution of such Contributor, if any, in source
                   code and object code form. This patent license
                   shall apply to the combination of the Contribution
                   and the Program if, at the time the Contribution is
                   added by the Contributor, such addition of the
                   Contribution causes such combination to be covered
                   by the Licensed Patents. The patent license shall
                   not apply to any other combinations which include
                   the Contribution. No hardware per se is licensed
                   hereunder.

                   c) Recipient understands that although each
                   Contributor grants the licenses to its
                   Contributions set forth herein, no assurances are
                   provided by any Contributor that the Program does
                   not infringe the patent or other intellectual
                   property rights of any other entity. Each
                   Contributor disclaims any liability to Recipient
                   for claims brought by any other entity based on
                   infringement of intellectual property rights or
                   otherwise. As a condition to exercising the rights
                   and licenses granted hereunder, each Recipient
                   hereby assumes sole responsibility to secure any
                   other intellectual property rights needed, if any.

                   For example, if a third party patent license is
                   required to allow Recipient to distribute the
                   Program, it is Recipient's responsibility to
                   acquire that license before distributing the
                   Program.

                   d) Each Contributor represents that to its
                   knowledge it has sufficient copyright rights in its
                   Contribution, if any, to grant the copyright
                   license set forth in this Agreement.

             3. REQUIREMENTS

             A Contributor may choose to distribute the Program in
             object code form under its own license agreement, provided
             that:
                   a) it complies with the terms and conditions of
                   this Agreement; and

                   b) its license agreement:
                   i) effectively disclaims on behalf of all
                   Contributors all warranties and conditions, express
                   and implied, including warranties or conditions of
                   title and non-infringement, and implied warranties
                   or conditions of merchantability and fitness for a
                   particular purpose;

                   ii) effectively excludes on behalf of all
                   Contributors all liability for damages, including
                   direct, indirect, special, incidental and
                   consequential damages, such as lost profits;

                   iii) states that any provisions which differ from
                   this Agreement are offered by that Contributor
                   alone and not by any other party; and

                   iv) states that source code for the Program is
                   available from such Contributor, and informs
                   licensees how to obtain it in a reasonable manner
                   on or through a medium customarily used for
                   software exchange.

             When the Program is made available in source code form:
                   a) it must be made available under this Agreement;
                   and
                   b) a copy of this Agreement must be included with
                   each copy of the Program. 

             Contributors may not remove or alter any copyright notices
             contained within the Program.

             Each Contributor must identify itself as the originator of
             its Contribution, if any, in a manner that reasonably
             allows subsequent Recipients to identify the originator of
             the Contribution. 


             4. COMMERCIAL DISTRIBUTION

             Commercial distributors of software may accept certain
             responsibilities with respect to end users, business
             partners and the like. While this license is intended to
             facilitate the commercial use of the Program, the
             Contributor who includes the Program in a commercial
             product offering should do so in a manner which does not
             create potential liability for other Contributors.
             Therefore, if a Contributor includes the Program in a
             commercial product offering, such Contributor ("Commercial
             Contributor") hereby agrees to defend and indemnify every
             other Contributor ("Indemnified Contributor") against any
             losses, damages and costs (collectively "Losses") arising
             from claims, lawsuits and other legal actions brought by a
             third party against the Indemnified Contributor to the
             extent caused by the acts or omissions of such Commercial
             Contributor in connection with its distribution of the
             Program in a commercial product offering. The obligations
             in this section do not apply to any claims or Losses
             relating to any actual or alleged intellectual property
             infringement. In order to qualify, an Indemnified
             Contributor must: a) promptly notify the Commercial
             Contributor in writing of such claim, and b) allow the
             Commercial Contributor to control, and cooperate with the
             Commercial Contributor in, the defense and any related
             settlement negotiations. The Indemnified Contributor may
             participate in any such claim at its own expense.


             For example, a Contributor might include the Program in a
             commercial product offering, Product X. That Contributor
             is then a Commercial Contributor. If that Commercial
             Contributor then makes performance claims, or offers
             warranties related to Product X, those performance claims
             and warranties are such Commercial Contributor's
             responsibility alone. Under this section, the Commercial
             Contributor would have to defend claims against the other
             Contributors related to those performance claims and
             warranties, and if a court requires any other Contributor
             to pay any damages as a result, the Commercial Contributor
             must pay those damages.


             5. NO WARRANTY

             EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE
             PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT
             WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR
             IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR
             CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR
             FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely
             responsible for determining the appropriateness of using
             and distributing the Program and assumes all risks
             associated with its exercise of rights under this
             Agreement, including but not limited to the risks and
             costs of program errors, compliance with applicable laws,
             damage to or loss of data, programs or equipment, and
             unavailability or interruption of operations. 

             6. DISCLAIMER OF LIABILITY
             EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER
             RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY
             FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
             OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION
             LOST PROFITS), 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 OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE
             OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE
             POSSIBILITY OF SUCH DAMAGES.

             7. GENERAL

             If any provision of this Agreement is invalid or
             unenforceable under applicable law, it shall not affect
             the validity or enforceability of the remainder of the
             terms of this Agreement, and without further action by the
             parties hereto, such provision shall be reformed to the
             minimum extent necessary to make such provision valid and
             enforceable.


             If Recipient institutes patent litigation against a
             Contributor with respect to a patent applicable to
             software (including a cross-claim or counterclaim in a
             lawsuit), then any patent licenses granted by that
             Contributor to such Recipient under this Agreement shall
             terminate as of the date such litigation is filed. In
             addition, If Recipient institutes patent litigation
             against any entity (including a cross-claim or
             counterclaim in a lawsuit) alleging that the Program
             itself (excluding combinations of the Program with other
             software or hardware) infringes such Recipient's
             patent(s), then such Recipient's rights granted under
             Section 2(b) shall terminate as of the date such
             litigation is filed.

             All Recipient's rights under this Agreement shall
             terminate if it fails to comply with any of the material
             terms or conditions of this Agreement and does not cure
             such failure in a reasonable period of time after becoming
             aware of such noncompliance. If all Recipient's rights
             under this Agreement terminate, Recipient agrees to cease
             use and distribution of the Program as soon as reasonably
             practicable. However, Recipient's obligations under this
             Agreement and any licenses granted by Recipient relating
             to the Program shall continue and survive. 

             Everyone is permitted to copy and distribute copies of
             this Agreement, but in order to avoid inconsistency the
             Agreement is copyrighted and may only be modified in the
             following manner. The Agreement Steward reserves the right
             to publish new versions (including revisions) of this
             Agreement from time to time. No one other than the
             Agreement Steward has the right to modify this Agreement.

             IBM is the initial Agreement Steward. IBM may assign the
             responsibility to serve as the Agreement Steward to a
             suitable separate entity. Each new version of the
             Agreement will be given a distinguishing version number.
             The Program (including Contributions) may always be
             distributed subject to the version of the Agreement under
             which it was received. In addition, after a new version of
             the Agreement is published, Contributor may elect to
             distribute the Program (including its Contributions) under
             the new version. Except as expressly stated in Sections
             2(a) and 2(b) above, Recipient receives no rights or
             licenses to the intellectual property of any Contributor
             under this Agreement, whether expressly, by implication,
             estoppel or otherwise. All rights in the Program not
             expressly granted under this Agreement are reserved.


             This Agreement is governed by the laws of the State of New
             York and the intellectual property laws of the United
             States of America. No party to this Agreement will bring a
             legal action under this Agreement more than one year after
             the cause of action arose. Each party waives its rights to
             a jury trial in any resulting litigation. 



*/

/************************************************************************
*                                                                       *
*      Copyright:       Corrent Corporation (c) 2001                    *
*                                                                       *
*      Filename:        typhoon.h                                       *
*      Created By:      Kapil Sood                                      *
*      Created On:      April 26, 2001                                  *
*      Description:     This is the main header file of the typhoon     *
*                       software library. This file contains all        *
*                       function declarations, data structures, type    *
*                       definitions, and data declarations that will    *
*                       be used in the typhoon software library.        *
*                                                                       *
*                                                                       *
************************************************************************/

/* Revision
 * $Id: typhoon.h,v 1.1 2005/01/18 16:09:03 kyoder Exp $
 */

#ifndef TYPHOON_H
#define TYPHOON_H

#ifdef __cplusplus
extern "C" {
#endif

#include <stdio.h>

/* Define Error and Warning file names */
#ifdef _UNIX
#define ERROR_FILE_NAME  "/tmp/error.dat"
#define WARNING_FILE_NAME  "/tmp/warning.dat"
#endif 

/* Define typedefs for data types used */

typedef unsigned char BYTE ;        /* 8-bit byte */
typedef unsigned short INT16 ;      /* 16-bit integer */
typedef unsigned int INT32 ;        /* 32-bit integer */

/* Define Endian-ness of the library */
typedef enum cr_endian_enum
    {
        CR_BIG_ENDIAN=0,
        CR_LITTLE_ENDIAN,
        CR_NETWORK_ENDIAN,

        /* Add all values above this */
        CR_MAX_ENDIAN
    } CR_ENDIAN ;

CR_ENDIAN cr_lib_endian ;

/* Define Return Code values */
typedef enum RC_enum
    {
        SUCCESS = 0,
        FAILURE = 1,

        /* Add all values above this */
        MAX_RC
    } RC ;

/* Define Crypto Algorithm Code */
typedef enum op_code_enum
    {
        CR_NULL_CRYPTO=0,
        CR_MOD_EXP,
        CR_MOD_EXP_CRT,
        CR_RSA_OP,
        CR_RSA_CRT_OP,
        CR_DSA_OP,
        CR_DES_CBC_ENC_OP,            
        CR_DES_CBC_DEC_OP,
        CR_DES_ECB_ENC_OP,            
        CR_DES_ECB_DEC_OP,
        CR_TDES_CBC_EDE_ENC_OP,     
        CR_TDES_CBC_EDE_DEC_OP,     
        CR_TDES_ECB_EDE_ENC_OP,     
        CR_TDES_ECB_EDE_DEC_OP,     
        CR_ARCFOUR_ENC_OP,           
        CR_ARCFOUR_DEC_OP,           
        CR_AES128_CBC_ENC_OP,        
        CR_AES128_CBC_DEC_OP,        
        CR_AES192_CBC_ENC_OP,       
        CR_AES192_CBC_DEC_OP,       
        CR_AES256_CBC_ENC_OP,         
        CR_AES256_CBC_DEC_OP,         
        CR_AES128_ECB_ENC_OP,         
        CR_AES128_ECB_DEC_OP,         
        CR_AES192_ECB_ENC_OP,         
        CR_AES192_ECB_DEC_OP,         
        CR_AES256_ECB_ENC_OP,
        CR_AES256_ECB_DEC_OP,

        CR_AUTHENTICATE_OP,             /* For all HMAC operations */

        /* Add all values above this */
        CR_MAX_OP_CODE         
   } CR_OP_CODE ;

typedef enum authenticate_code_enum
    {
        CR_NULL_AUTH=0,
        CR_SHA1,                     /* Perform SHA-1 hash */
        CR_HMAC_SHA1,                /* Perform HMAC_SHA-1 */
        CR_HMAC_SHA1_96,             /* Perform HMAC_SHA-1-96 */
        CR_MD5,                      /* Perform MD5 hash */
        CR_HMAC_MD5,                 /* Perform HMAC_MD5 hash */
        CR_HMAC_MD5_96,              /* Perform HMAC_MD5-96 */
        CR_MD5_SHA1,                 /* Perform MD5 and SHA1 hashes separately */
        CR_DBL_SHA1,                 /* Perform SHA1 twice */
        CR_DBL_MD5,                  /* Perform MD5 twice */
        CR_DBL_SHA1_MD5,             /* Perform MD5 inside and SHA-1 outside */
        CR_DBL_MD5_SHA1,             /* Perform SHA-1 inside and MD5 outside */ 
        CR_PRF,                      /* Perform PRF */

        /* Add all values above this */
        CR_MAX_AUTH_CODE
    } CR_AUTH_CODE ;

/* Define the RSA padding/encryption type */
typedef enum rsa_type_enum
    {
        CR_NULL_RSA = 0,
        CR_PKCS1_1_5 = 1,                 /* Perform PKCS1_1.5 used in SSLv3/TLS1.0 */

        /* Add all values above this */
        CR_MAX_RSA_TYPE
    } CR_RSA_TYPE ;

/* Define typedefs for complex data structures used */
typedef struct token_struct
     {
         BYTE    *p_data ;       /* The pointer to actual data */
         INT32   data_size ;     /* The length (in bytes) of the data */
     } token ;
typedef struct rsa_key_struct
    {
         token   *modulus ;       /* 'n' */
         token   *exponent ;      /* Can be 'e' or 'd' */
    } rsa_key ;
typedef struct rsa_crt_key_struct
    {
         token   *prime_p ;
         token   *prime_q ;
         token   *dmp1 ;           /* 'd mod (p-1)' value */
         token   *dmq1 ;           /* 'd mod (q-1)' value */
         token   *iqmp ;           /* 'inv(q) mod p' value */  
    } rsa_crt_key ;
typedef struct dsa_sign_key_struct
    {
         token   *r ;
         token   *s ;
    } dsa_sign_key ;
typedef struct dsa_key_struct
    {
         token   *p ;
         token   *q ;
         token   *g ;
         token   *key ;    /* sign: server private key(x); verify: client public key(y) */
    } dsa_key ;

/* The following struct is used as a general purpose structure for DES encryption/decryption
   operations. Each of the DES keys are 56-bit long, as per DES specifications. However, the
   last bit of each byte is used for parity checking. Therefore, the total key size for each key
   is 64-bit. If single/double keys are used, then unused keys must be NULL, and NULL keys must
   follow the valid keys. The Initialization Vector (iv) is also 64-bit long.               */
typedef struct des_key_struct
    {
         token   *iv ;
         token   *key1 ;     
         token   *key2 ;   
         token   *key3 ;
    } des_key ;

/* The following struct is used as the key for ARCFOUR. The length of the key 
 * may be between 1 and 256 bytes. However, SSLv3 and TLS1.0 use ARC4 with 128bit
 * (16 Bytes) key length. Use either the static key, or key token.
 */
typedef struct arcfour_key_struct
    {
         token         *key ; 
         unsigned char state[256] ;
         unsigned char state_x ;
         unsigned char state_y ;
    } arcfour_key ;

/* The following struct is used as a key for AES. The length of the key must be 128/192/256
   bits for AES128/AES192/AES256 respectively. The iv must also be of appropriate sizes */
typedef struct aes_key_struct
    {
         token   *key ;
         token   *iv ;
    } aes_key ;

/* The following struct is used for defining secret key components for HMAC algorithms. 
   The size of i/odigest component will be 16/20 Bytes, depending on the hash algorithm 
   MD5/SHA1. The I/ODigest values are the 64B extention of the secret key, XORed with 
   ipad/opad, and then hash operated. Alternatively, the application could send the
   secret into the library, and the Typhoon device will handle the entire computation.
   If an ordinary MD5 or SHA1 hashing operation is required, there is no need to use 
   this structure. */
typedef struct hmac_key_struct
    {
         token   *secret ;
         token   *idigest ;
         token   *odigest ;
    } hmac_key ;

/* The following struct is used for defining secret keys for TLS1.0 PRF algorithms. 
   The PRF key components will be either the secret, or the I/ODigest for HMAC_MD5 and 
   HMAC_SHA1. If the secret is NULL, then all other components must contain valid
   values. If secret is not NULL, then the secret will be used by the library. 
   If the secret is not NULL, then other components must be NULL or will be ignored. */
typedef struct prf_key_struct
    {
         token      *secret ;
         BYTE       *idigest_md5 ;
         BYTE       *odigest_md5 ;
         BYTE       *idigest_sha1 ;
         BYTE       *odigest_sha1 ;
    } prf_key ;

/* The following structure will be used for passing SSLv3 and TLS1.0 security
   parameters into the library. These security parameters will be unique for 
   every SSL/TLS connection and direction. The tls_mac_key must be used for
   TLS1.0 only, and the sslv3_tls_mac_secret for SSLv3. 
   The symmetric keys will either be DES/3DES or ARC4. */
typedef struct sslv3_tls_key_struct
    {
        CR_AUTH_CODE       auth_code ;
        CR_OP_CODE         crypto_code ;
        hmac_key           *tls_hmac_key ;
        token              *sslv3_mac_secret ;
        union 
        {
            des_key        *des_sym_key ;
            arcfour_key    *arcfour_sym_key ;
        } sym_key ;
    } sslv3_tls_key ;

/* The following are the SA flags that will be used with IPSEC processing.
 * CR_AH_ADDPAD
 * CR_AH_NEXT_HDR_STRIP - If set for ESP inbound packets the next header byte
 *                        will be removed from the packet after decryption.
 * CR_IV_STRIP          - If set for ESP inbound packets the IV is removed
 *                        from the IPsec header.
 * CR_OHDR_STRIP        - If set then all bytes up to the data are removed.
 * CR_MIN_PADEN         - If set for outbound packets then the packet is
 *                        padded to the multiple of the cipher block size.
 *                        For NULL cipher the packet is padded to a multiple
 *                        of 4 bytes.
 * CR_ENCRYPT           - Set for outbound ESP packets. Cleared for inbound.
 */
#define CR_AH_ADDPAD       0x00000001
#define CR_NEXT_HDR_STRIP  0x00000002
#define CR_IV_STRIP        0x00000004
#define CR_OHDR_STRIP      0x00000008
#define CR_MIN_PADEN       0x00000010
#define CR_ENCRYPT         0x00000020

/* Data structure for storing key information for IPsec AH & ESP packets.
 * auth_code   - Authentication type. Must be set for AH. Can be NULL for ESP.
 * crypto_code - Cipher type for ESP packets. Must be CR_AUTHENTICATE_OP for
 *               AH.
 * sa_flags    - Flags to set in the SA from the list above.
 * hmac_key    - Mac Secret for authentication. Can be NULL if no auth.
 * sym_key     - Union of DES and AES key pointers. crypto_code is checked
 *               to determine which key to use if any. Ignored for AH mode.
 * NOTE: auth_code and crypto_code cannot both be NULL.
 */
typedef struct ipsec_key_struct
    {
        CR_AUTH_CODE       auth_code ;
        CR_OP_CODE         crypto_code ;
        INT32              sa_flags ;
        hmac_key           *hmac_key ;

        union
        {
            des_key    *des_sym_key ;
            aes_key    *aes_sym_key ;
        } sym_key ;
    } ipsec_key ;

/* Data structures and defines for returning statistics into the library.
 * The same structure will be passed into the driver. 
 */

#ifndef CR7020_STATS_HDR
#define CR7020_STATS_HDR

#define CR7020_MAX_STATS             20 
#define CR7020_MAX_STAT_NAME_LEN     30 
 
typedef struct cr_key_value_pair
        {
                char              key[CR7020_MAX_STAT_NAME_LEN] ;
                unsigned long     value ;
        } cr_key_value_pair;
 
typedef struct cr_stat_table
        {
                union
                {
                        cr_key_value_pair       cr7020_stat[CR7020_MAX_STATS] ;
                } dev ;
        } cr_stat_table;
 
cr_stat_table    cr7020_stat_table ;

#endif /* CR7020_STATS_HDR */                                                                                      

#ifndef CR_DEVICE_INFO
#define CR_DEVICE_INFO

typedef struct cr_device_info_struct {
        unsigned char driver_version[8];
        unsigned int device;
        unsigned int device_status;
        unsigned char pci_bus_num;
        unsigned char pci_dev_num;
        unsigned char pci_func_num;
} cr_device_info;

#endif /* CR_DEVICE_INFO */                                                                                      

/* ##################################################################### */
/*                 Define Function Prototypes                            */
/* ##################################################################### */

/**************************************************************************
                         Numerical Functions
***************************************************************************/

/* The following function is used for retrieving a random number. The desired
   length of the random is specified in the size parameter.  The random number 
   is returned in result buffer, along with the byte size.               */
RC CR_get_random(token *result, INT32 size) ;
   
/* This function will be used for returning strong DES keys, each 8 byte in
   size. The number of keys is specified in the count parameter. The result
   token will be filled with the 'count' number of DES keys concatenated
   in one string. The result size component will contain the length of the
   DES key string in bytes.                                             */
RC CR_get_des_keys(token *result, INT32 count) ;

/* This function is used for returning a prime number of a desired length
   (in bytes). This length is specified in the size parameter. The prime 
   number is returned in the result buffer, along with the size in bytes */
RC CR_get_prime(token *result, INT32 size) ;

/* The following function is used for performing mod operations (a mod n) on the
   argument, and returns the result. The argument must be in the octet format. */
RC CR_mod(token *result, token *argument, token *modulus) ;

/* The following function is used for performing mod exp (a^e mod n) operations 
   on the argument, and returns the result. This uses Montgomery exponentiation
   method. The argument must be in the octet format and it DOES require a modulo
   reduction being already done. */
RC CR_mod_exp_mont(token *result, token *argument, token *modulus, token *exponent) ;

#ifdef TYPHOON_B
/* The following function is used for performing mod exp (a^e mod n) operations
   on the argument, and returns the result. This uses Montgomery exponentiation
   method. The argument must be in the octet format and DOES NOT require a 
   modulo reduction. */
RC CR_mod_exp_mont_with_reduction(token *result, token *argument, token *modulus,
                                  token *exponent) ;
#endif /* TYPHOON_B */

/* The following function is used for performing mod exp (a^e mod n) operations 
   using the Chinese Remainder Theorem. This operation may be used for the RSA
   private key decrypt, and RSA signing operations. The argument must be in 
   the octet format.                                                    */
RC CR_mod_exp_crt(token *result, token *argument, token *prime_p, token *prime_q, 
                  token *dmp1, token *dmq1, token *iqmp) ;

/* The following function is used for performing mod_add (a+b mod n) operations 
   on the arguments, and returns the result. The argument must be in the octet format. */
RC CR_mod_add(token *result, token *a_arg, token *b_arg, token *modulus) ;

/* The following function is used for performing mod_mult (a*b mod n) operations 
   on the arguments, and returns the result. This operation uses Montgomery 
   multiplication method. The argument must be in the octet format. */
RC CR_mod_mult_mont(token *result, token *a_arg, token *b_arg, token *modulus) ;

/* The following function will compute 'inv(k) mod n' operation on the
   argument (k) that is passed in along with the modulus (n). */
RC CR_inv_mod(token *result, token *k, token *modulus) ;

/* The following function will be used for computing the value of R^2 mod N,
   where R^2 = 2^(2*(k+8)) and 'k' is size of N in bytes */
RC CR_r_sqr_mod_n(token *result, token *modulus) ;

/**************************************************************************
                         Public-Key Crypto Functions
***************************************************************************/

/* The following function is used for performing RSA encrypt operations on the
   argument, and returns the result. The 'argument' is in the octet string 
   format. This function performs rsa_type operations to encrypt the argument.
   The exponent is the public key 'e' component of the recipient. 
   The trans_id is used for debug/error tracking and is optional (can be NULL) */
RC CR_rsa_encrypt(token *ciphertext, BYTE *trans_id, token *argument, CR_RSA_TYPE rsa_type,
                  rsa_key *key) ;

/* The following function is used for performing RSA decrypt operations on the
   argument, and returns the result. The 'argument' is the ciphertext in the octet 
   string format. This function performs rsa_type operations to decrypt the argument.
   The rsa_key->exponent is the private key 'd' of the recipient. 
   The trans_id is used for debug/error tracking and is optional (can be NULL) */
RC CR_rsa_decrypt(token *plaintext, BYTE *trans_id, token *argument, CR_RSA_TYPE rsa_type,
                  rsa_key *key) ;

/* The following function is used for performing RSA decrypt operations on the
   argument, and returns the result. The 'argument' is the ciphertext in the octet 
   string format. This function performs PKCS#1 operation, specified by rsa_type,
    to decrypt the argument. 
   The rsa_key->exponent is the private key 'd' of the recipient. 
   The trans_id is used for debug/error tracking and is optional (can be NULL) */
RC CR_rsa_decrypt_crt(token *plaintext, BYTE *trans_id, token *argument, 
                      CR_RSA_TYPE rsa_type, rsa_crt_key *key) ;

/* The following function is used for performing RSA private key decrypt ops on the
   argument, and returns the original msg that was encrypted. The 'argument' is 
   in the octet string format. This function does NOT perform any padding ops, and 
   is designed to be used by an external RSA_decrypt() function. The result is of 
   the same size as the modulus, which means that it may have leading zeros.
   The rsa_key->exponent is the private key 'd' of the recipient.
   The trans_id is used for debug/error tracking and is optional (can be NULL)  */
RC CR_rsa_private_decrypt(token *plaintext, BYTE *trans_id, token *argument, rsa_key *key) ;

/* The following function performs RSA private key decrypt operations, using CRT,
   on the argument, and returns the original msg. The 'argument' is in the octet string
   format. This function does not perform any padding operations, and will be used by an
   external RSA_decrypt function. The result is of the same size as the modulus, which 
   means that it may have leading zeros. 
   The trans_id is used for debug/error tracking and is optional (can be NULL) */
RC CR_rsa_private_decrypt_crt(token *plaintext, BYTE *trans_id, token *argument,
                              rsa_crt_key *key) ;

/* The following function is used for performing RSA signing operations on the
   argument, and returns the signature. The 'argument' is in the octet string 
   format. This function performs PKCS#1 encoding operations, as specified by
   rsa_type to generate the signature. The hash_code value depends on the 
   protocol requesting the signing.  
   The trans_id is used for debug/error tracking and is optional (can be NULL) */
RC CR_rsa_sign(token *signature, BYTE *trans_id, token *argument, CR_RSA_TYPE rsa_type,
               rsa_key *key, CR_AUTH_CODE hash_code) ;

/* The following function uses CRT for performing RSA signing operations on the
   argument, and returns the signature. The 'argument' is in the octet string 
   format. This function performs PKCS#1 encoding operations, as specified 
   by rsa_type, to generate the signature. The hash_code value depends on the
   the protocol requesting the signing.  
   The trans_id is used for debug/error tracking and is optional (can be NULL) */
RC CR_rsa_sign_crt(token *signature, BYTE *trans_id, token *argument, CR_RSA_TYPE rsa_type,
                   rsa_crt_key *key, CR_AUTH_CODE hash_code) ;

/* The following function is used for performing RSA signature verification operations 
   on the 'signature', and returns the message. The received signature is in the 
   octet string format. This function performs PKCS#1 operation, as specified by
   rsa_type, to generate the message signed by sender. The rsa_key->exponent is 
   the public key 'e' component of the sender. The computed message is in the 
   octet string format. This function also compares the computed 'message' with 
   the original message to verify the signature. This function returns SUCCESS 
   if the signatures are valid, and FAILURE otherwise. 
   The trans_id is used for debug/error tracking and is optional (can be NULL) */
RC CR_rsa_verify(token *message, BYTE *trans_id, token *signature, CR_RSA_TYPE rsa_type,
                 rsa_key *key, CR_AUTH_CODE hash_code) ;

/* The following function is used for performing RSA public key decrypt operation,
   which will be used by external RSA_verify function.
   The received signature is in the octet string format. This function performs
   PKCS#1 mod_exp operation, to generate the original encoded message which was 
   signed by sender. This function returns the PKCS#1 encoded original message 
   in sign_decrypted token.
 */
RC CR_rsa_public_decrypt(token *sign_decrypted, BYTE *trans_id, token *signature,
                         rsa_key *key) ;

/* The following function is used for signing the SHA-1 hashed message. If the passed
   random number pointer is NULL, then the library internally generates a random number.
   This function returns the signature components 'r' and 's' in dsa_sign struct. 
   The trans_id is used for debug/error tracking and is optional (can be NULL) */
RC CR_dsa_signature(dsa_sign_key *signature, BYTE *trans_id, token *msg_hash, 
                    dsa_key *key, token *random_k) ;

/* The following function is used for verifying the DSA signatures on the message
   (hash_msg_recd). The received signatures that were used to sign this hash_msg_recd
   must be passed.  This returns a value indicating if the signatures match (RC=SUCCESS) 
   or do not match (RC=FAILURE). 
   The trans_id is used for debug/error tracking and is optional (can be NULL) */
RC CR_dsa_verify(BYTE *trans_id, token *msg_hash_recd, dsa_sign_key *signature_recd, 
                 dsa_key *key) ;

/**************************************************************************
                         Symmetric Crypto Functions
***************************************************************************/

/* The following function is used for performing encryption operations 
   on the data (plaintext). The trans_id identifies key which contains information, 
   internal to the library, about the cipher algorithm.                         */  
RC CR_encrypt(token *ciphertext, BYTE *trans_id, token *plaintext) ;

/* The following function is used for performing decryption operations 
   on the data (ciphertext). The trans_id identifies key which contains information, 
   internal to the library, about the cipher algorithm.                         */  
RC CR_decrypt(token *plaintext, BYTE *trans_id, token *ciphertext) ;

/* The following function performs entire SSLv3 outbound record layer processing. The
   processing steps include SSLv3 record layer MAC generation (ignoring version
   field), padding (for block ciphers only), and encryption. The sequence number 
   is a 64-bit number that the application must pass as an 8-byte string.      */
RC CR_encrypt_sslv3_record(token *sslv3_ciphertext, BYTE *trans_id, BYTE *seq_num,
                           token *sslv3_compressed) ; 

/* The following function performs entire SSLv3 inbound record layer processing. The
   processing steps include SSLv3 record layer decryption, MAC generation w/o version
   field and verification, verification and removal of padding (for block ciphers only), 
   and update length field. The sequence number is a 64-bit number that the application 
   must pass as an 8 Byte string. RC=SUCCESS indicates that there was no error in
   decrypting the record, and RC=FAILURE indicates an error (MAC verify, Seq Number check,
   Pad verify, or system error) occurred while processing the record.            */
RC CR_decrypt_sslv3_record(token *sslv3_compressed, BYTE *trans_id, BYTE *seq_num,
                           token *sslv3_ciphertext) ; 

/* The following function performs entire TLS1.0 outbound record layer processing. The
   processing steps include TLS1.0 record layer MAC generation (using HMAC)
   padding (for block ciphers only), and encryption. The sequence number is a 
   64-bit number that the application must pass as an 8-byte string.             */
RC CR_encrypt_tlsv1_record(token *tlsv1_ciphertext, BYTE *trans_id, BYTE *seq_num,
                           token *tlsv1_compressed) ; 

/* The following function performs entire TLS1.0 inbound record layer processing. The
   processing steps include TLS1.0 record layer decryption, MAC generation 
   and verification, verification and removal of padding (for block ciphers only), 
   and update length field. The sequence number is a 64-bit number that the application 
   must pass as an 8 Byte string. RC=SUCCESS indicates that there was no error in
   decrypting the record, and RC=FAILURE indicates an error (MAC verify, Seq Number check,
   Pad verify, or system error) occurred while processing the record.            */
RC CR_decrypt_tlsv1_record(token *tlsv1_compressed, BYTE *trans_id, BYTE *seq_num,
                           token *tlsv1_ciphertext) ; 

/* The following function performs entire SSLv3 outbound record layer
   processing, which has a key passed along with the record.  This function is
   a combination of the CR_insert_sslv3_key() and CR_encrypt_sslv3_record(),
   which performs these 2 tasks using a single ioctl command. This function
   will also update the SA and chip numbers in the library.
   input: trans_id - The transaction identifier that identifies the key
                     and cipher/hash, inside the library
          sslv3_compressed - The compressed SSL record data and size
          seq_num - The sequence number with MSB in byte 0 location
          update_key - Whether the IVs/StateVars for ciphers be read back. For
                 ARCFOUR, the state array, state_x, state_y will be updated.
                 For (T)DES CBC, the original IV will be updated with that read
                 from CR7020 DDR.
   output: sslv3_ciphertext - The encrypted/HMACed SSLv3 record data and size
 */
RC CR_encrypt_sslv3_with_key( token *sslv3_ciphertext, BYTE *trans_id,
                              BYTE *seq_num, token *sslv3_compressed,
                              INT32 key_struct_address, BYTE update_key ) ;

/* The following function performs entire TLS1.0 outbound record layer
   processing, which has a key passed along with the record.  This function is
   a combination of the CR_insert_tlsv1_key() and CR_encrypt_tlsv1_record(),
   which performs these 2 tasks using a single ioctl command. This function
   will also update the SA and chip numbers in the library.
   input: trans_id - The transaction identifier that identifies the key
                     and cipher/hash, inside the library
          tlsv1_compressed - The compressed TLS record data and size
          seq_num - The sequence number with MSB in byte 0 location
          update_key - Whether the IVs/StateVars for ciphers be read back. For
                 ARCFOUR, the state array, state_x, state_y will be updated.
                 For (T)DES CBC, the original IV will be updated with that read
                 from CR7020 DDR.
   output: tlsv1_ciphertext - The encrypted/HMACed SSLv3 record data and size
 */
RC CR_encrypt_tlsv1_with_key( token *tlsv1_ciphertext, BYTE *trans_id,
                              BYTE *seq_num, token *tlsv1_compressed,
                              INT32 key_struct_address, BYTE update_key ) ;

/* Encrypts an IPsec packet using the ESP protocol. The input token
 * esp_plaintext should contain the outer IP header, followed by 8 bytes
 * for the SPI & sequence number, followed by the data packet, followed by
 * the 1 byte for the next header. oheader_len should be set to the length
 * of the outer IP header in bytes. The returned esp_ciphertext will be
 * filled with the encrypted packet, padding, and authentication MAC if
 * used.
 */
RC CR_encrypt_ipsec_esp( token *esp_ciphertext, BYTE *trans_id,
                         token *esp_plaintext, unsigned int oheader_len );

/* Decrypts an IPsec packet using the ESP protocol. The input token
 * esp_ciphertext should contain the outer IP header, followed by 8 bytes
 * for the SPI & sequence number, followed by the IV & encrypted data
 * packet (including pad & next header bytes), followed by an optional
 * MAC. The oheader_len should be set to the length of the outer header in
 * bytes. The MAC, if used, is verified and discarded and the payload
 * decrypted. The outer header, next header, and IV will be either returned
 * or stripped depending on the SA flags used when initializing the
 * transaction.
 */
RC CR_decrypt_ipsec_esp( token* esp_plaintext, BYTE* trans_id,
                         token* esp_ciphertext, unsigned int oheader_len );

/* Computes the MAC for an IPsec packet using the AH protocol. The input
 * token ah_plaintext should contain the outer IP header followed by
 * 8 bytes for the SPI and sequence number followed by the packet.
 * The oheader_len should contain the length of the outer header in
 * bytes. The MAC is computed and returned in ah_ciphertext. Note that
 * the payload data itself is not returned. Also note that any mutable
 * fields in the outer IP header must be zeroed out before calling this
 * function.
 */
RC CR_encrypt_ipsec_ah( token* ah_ciphertext, BYTE* trans_id,
                        token* ah_plaintext, unsigned int oheader_len );

/* Verifies the MAC for an IPsec packet using the AH protocol. The input
 * token ah_ciphertext should contain the outer IP header followed by 8
 * bytes for the SPI and sequence number followed by the MAC followed by
 * the packet. The oheader_len should contain the length of the outer header
 * in bytes. The MAC is verified and SUCCESS returned if it is valid. Note
 * that no data is returned. Also note that any mutable fields in the outer
 * IP header must be zeroed out before calling this function.
 */
RC CR_decrypt_ipsec_ah( BYTE* trans_id, token* ah_ciphertext,
                        unsigned int oheader_len );

/* This function is used for performing hash/HMAC operations on the argument. This
   function requires an algorithm auth_code. The secret key(s) for HMAC were passed in 
   separately, if trans_id is not NULL. If trans_id is NULL, then the secret_key must be
   valid for HMAC.  
              Definition: HMAC_hash(secret_key, argument)    
   For performing hash operation without secret_key: trans_id will be NULL, and 
   secret_key will be NULL. For hash operation with secret_key, the key must be
   part of the argument(s), and trans_id must be NULL, and secret_key components
   must be NULL.
   inner_argument will be NULL for single hash and HMAC operations. outer_argument
   will be used for single, double, and HMAC operations.                         */
RC CR_authenticate(token *digest, BYTE *trans_id, CR_AUTH_CODE auth_code, token *inner_argument,
                   token *outer_argument, hmac_key *secret_key) ; 

/* The following function will be used for performing the Hash_Init
   operation for SHA1 and MD5. This function will internally create
   a context for a new hash operation series and associate it with the
   given transaction id.
   input: trans_id - The transaction id.
          auth_code - The Hash code, either SHA1 or MD5
   output: context - Not used.
           RC must be SUCCESS */
RC CR_HashInit(BYTE *trans_id, void **context, CR_AUTH_CODE auth_code) ;

/* The following function will be used for performing incremental hash operations
   for MD5 and SHA1. The application will pass-in the address to the cr_hash_ctx
   structure. This function will accumulate the passed-in data until the size
   exceeds 64 Bytes, in which case, this function will pass all data with a
   size which is a multiple of 64 to the device for processing.
   input: trans_id - Transaction id passed to HashInit
          context - Ignored
                previous successful call to CR_HashInit
          arg - The input data and size to be incrementally processed for
                the hash op specified in the cr_hash_ctx struct.
   output: RC must be SUCCESS */
RC CR_HashUpdate(BYTE *trans_id, void *context, token *arg) ;

/* The following function will be used for performing the final hash operation
   for MD5 and SHA1. The application will pass-in the address to the cr_hash_ctx
   structure. This function will add necessary padding to the remaining bytes in
   the ctx buffer, and perform the final hash processing. This function will also
   cleanup the ctx data structure and the SA in the device.
   input: trans_id - Transaction id passed to HashInit
          context - Ignored
   output: result - The application must allocate memory (16B for MD5/20B for SHA1)
                    for getting the final digest
           RC must be SUCCESS */
RC CR_HashFinal(BYTE *result, BYTE *trans_id, void *context) ;

/* The following function is used for performing the Pseudo Random Function (PRF)
   operation on the argument (seed) and label, and setting the desired length in the 
   result parameter. The prf output hash will be placed in result.  If the trans_id
   is NULL, all the components of prf_key: secret, OR, idigest_md5, odigest_md5, 
   idigest_sha1, odigest_sha1 must be valid. If trans_id is not NULL, the secret keys 
   were passed in separately, and if passed in here, they will be ignored.
          Definition: PRF(secret_key,label,seed)[desired_length]               */
RC CR_prf(token *result, BYTE *trans_id, token *seed, token *label, prf_key *secret_key) ;

/**************************************************************************
                         Transaction Functions 
***************************************************************************/

/* The following function is used for initiating a new transaction. This function
   returns a pointer to the transaction identifier, if success, or 
   NULL, if failed.    */
BYTE *CR_new_transaction(void) ;

/* The following function is used for removing a transaction from the system.
   This function requires that a valid pointer, preferably the same as returned
   by CR_new_transaction(), is used as the argument. This function will free
   the memory associated to store the trans_id value. */
RC CR_delete_transaction(BYTE *trans_id) ;

/* The following function returns the SA address in Typhoon's DDR memory,
   corresponding to the transaction identifier that is passed into this
   function. */
RC CR_get_sa_address(INT32 *sa_address, BYTE *trans_id) ;

/* The following function is used to upload a new key into the system. The
   op_code/auth_code will identify the crypto/hash algorithm for these keys.
   The library will use these codes to interpret the address pointer of
   the appropriate crypto/hash struct like des_key, aes_key, and other key
   structures identified in the header file.  Please note that for auth_code
   to be used, the value of op_code must be AUTHENTICATE_OP, otherwise the
   value of auth_code will be ignored. Application doesn't create a key for
   hash operations, the library will generate those keys. The application 
   needs to create the keys for HMAC operations only. Also, the application
   cannot establish keys for RSA and DSA operations.                    */
RC CR_insert_cipher_key(BYTE *trans_id, CR_OP_CODE op_code, CR_AUTH_CODE auth_code, 
                        INT32 key_struct_address) ; 

/* The following function will be used for inserting SSLv3 security parameter
   values into the library. The address pointer will point to the sslv3_tls_key 
   struct. This function will cross verify the input data parameters. This security
   parameter struct contains all the keys necessary to perform encryption/decryption
   and MAC operations.                                                                */
RC CR_insert_sslv3_key(BYTE *trans_id, INT32 key_struct_address) ;

/* The following function will be used for inserting TLS1.0 security parameter
   values into the library. The address pointer will point to the sslv3_tls_key 
   struct. This function will cross verify the input data parameters. This security
   parameter struct contains all the keys necessary to perform encryption/decryption
   and HMAC operations.                                                                */
RC CR_insert_tls_key(BYTE *trans_id, INT32 key_struct_address) ;

/* Inserts an ipsec_key into the device SA memory. If crypto_code in the
 * device is set or NULL then the key is inserted as an ESP packet. If
 * crypto_code is set to CR_AUTHENTICATE_OP then the key is inserted as
 * an AH packet.
 */
RC CR_insert_ipsec_key( BYTE* trans_id, INT32 key_struct_address ) ;

/* The following function will be used for inserting the PRF keys in the library.
   The key_struct_address is the address of the structure prf_key */
RC CR_insert_prf_key(BYTE *trans_id, INT32 key_struct_address) ;

/* The following function is used to delete a key from the system. */
RC CR_delete_key(BYTE *trans_id) ; 

/**************************************************************************
                         Administrative Functions 
***************************************************************************/

/* The following function will return the version number of the CR702X
   library.
   Returns the library version number in lib_ver buffer. Make sure at least
   20 bytes are allocated for this buffer. */
RC CR_get_libver(BYTE *lib_ver) ;

/* This function will initialize the entire software library. This means
   cleaning all the on-going operations, deleting all stored data, freeing
   all allocated memory, and insering intial data (as required). This function
   also contains (optional) error and warning file pointers. If these are NULL,
   then the function will create the files identified in this header file  */
RC CR_init_lib(FILE *error_file, FILE *warning_file) ;

/* This function will be called to close all existing devices that the
   library is using. In addition, all unused data structures. */
RC CR_close_lib(void) ;

/* This function will set the endian-ness of the library to BIG, LITTLE, or
   NETWORK endian order.  This means that the library will accept/interpret
   data from the application in the order that is set by this function. By
   default, the library is set to BIG endian.   */
void CR_set_endian(CR_ENDIAN endian) ;

/* The following function is used for testing the random number generator. The 
   randomizer runs the FIPS tests on a sample of random data, which is generated
   internally, and returns a SUCCESS if the random data passed the FIPS test, 
   and FAILURE, otherwise.        */
RC CR_test_random(void) ;

/* This function will be used for resetting the various sub-components
   of the device driver.                                             */
RC CR_init_random(void) ;

/* The following function deletes all on-going transactions in the library,
   and resets the transaction related data structures */
RC CR_init_transaction(void) ;

/* The following function will fill the stats table in the library,
   and add the key names to the table.  This function will be called a single
   time, as part of the library initialization. The stat table will be updated
   by the CR_get_stat() function.
*/
RC CR_init_stat(void) ;
 
/* The following function is used for capturing the stats from the
   driver, and returning the data to the calling application. The
   library allocated static memory structure (stat table) at init time (in
   the function CR_init_stat()), which is cleaned up when program ends.
   Input:  None
   Output: cr_stat_table: Pointer to the stat table in library memory.
                          Returns NULL pointer on FAILURE.
*/
cr_stat_table *CR_get_stat(void) ;

/* The following function is used for obtaining device information from
   the driver.
   Input:  None
   Output: cr_device_info: Pointer to the device info structure in library.
                           memory. 
                           Returns NULL pointer on FAILURE.
*/
cr_device_info *CR_get_device_info(void) ;

/* The following function is used to perform a selftest on the CR7020/CR7120
   device.
   Input:  None
   Output: SUCCESS if selftest passed or FAILURE, otherwise.
*/
RC CR_perform_selftest( void );

/***************************************************************************
                               END OF APIs 
***************************************************************************/


#ifdef __cplusplus
}
#endif

#endif
