/*
             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. 



*/

/* (C) COPYRIGHT International Business Machines Corp. 2001          */


#include <pthread.h>
#include <string.h>            // for memcmp() et al
#include <strings.h>
#include <stdlib.h>

#ifndef NOAES
#include <openssl/aes.h>
#endif
#ifndef NODH
#include <openssl/dh.h>
#endif

#include "pkcs11types.h"
#include "defs.h"
#include "host_defs.h"
#include "h_extern.h"

#include "tok_specific.h"
#include "tok_struct.h"

#include "ica_api.h"
// declare the adapter open handle localy
ICA_ADAPTER_HANDLE adapter_handle;

// Linux really does not need these so we just dummy them up
// so the common code across platforms is usable...
#define KEYTYPE_MODEXPO   1
#define KEYTYPE_PKCSCRT   2

CK_CHAR manuf[] = "IBM Corp.";
CK_CHAR model[] = "IBM ICA     ";
CK_CHAR descr[] = "IBM PKCS#11 ICA token ";
CK_CHAR label[] = "IBM ICA  PKCS #11";



pthread_mutex_t  rngmtx = PTHREAD_MUTEX_INITIALIZER;
unsigned int  rnginitialized=0;



CK_RV
token_rng(CK_BYTE *output, CK_ULONG bytes)
{
   unsigned int  rc;

      pthread_mutex_lock(&rngmtx);

      rc = icaRandomNumberGenerate(adapter_handle, (unsigned int)bytes, output);

      if (rc != 0) {
         pthread_mutex_unlock(&rngmtx);
         st_err_log(3, __FILE__, __LINE__);
         return CKR_GENERAL_ERROR;
         /* report error */
      }

      pthread_mutex_unlock(&rngmtx);
      return CKR_OK;

}

int
tok_slot2local(CK_SLOT_ID snum)
{
   return 1;
}

CK_RV
token_specific_init(char * Correlator,CK_SLOT_ID  SlotNumber)
{

   return icaOpenAdapter(0,&adapter_handle);
}

CK_RV
token_specific_final()
{
   icaCloseAdapter(adapter_handle);
   return CKR_OK;
}

// count_ones_in_byte: for use in adjust_des_key_parity_bits below
CK_BYTE 
count_ones_in_byte(CK_BYTE byte)
{  
   CK_BYTE and_mask,   // bit selector
           number_of_ones = 0;

   for (and_mask = 1; and_mask != 0; and_mask <<= 1) // for each bit,
      if (byte & and_mask) // if it's a one,                         
         ++number_of_ones; // count it

   return number_of_ones;
}

#define EVEN_PARITY TRUE
#define ODD_PARITY FALSE
 // adjust_des_key_parity_bits: to conform to NIST spec for DES and 3DES keys
void adjust_des_key_parity_bits(CK_BYTE *des_key, CK_ULONG key_size, CK_BBOOL parity)
{
   CK_BYTE *des_key_byte;

   for (des_key_byte = des_key; des_key_byte - des_key < key_size; ++des_key_byte)
         // look at each byte in the key
   {
      if ((count_ones_in_byte(*des_key_byte) % 2) ^ (parity == ODD_PARITY))
      {
         // if parity for this byte isn't what it should be,
         // flip the parity (least significant) bit
         *des_key_byte ^= 1;
      }
   }
}







CK_RV
token_specific_des_key_gen(CK_BYTE  *des_key,CK_ULONG len)
{
      
   // Nothing different to do for DES or TDES here as this is just
   // random data...  Validation handles the rest
        rng_generate(des_key,len);
        adjust_des_key_parity_bits(des_key, len, ODD_PARITY);

        
   // we really need to validate the key for parity etc...
   // we should do that here... The caller validates the single des keys
   // against the known and suspected poor keys..<<
        return CKR_OK;

}

CK_RV
token_specific_des_ecb(CK_BYTE * in_data,
                       CK_ULONG in_data_len,
                       CK_BYTE *out_data,
                       CK_ULONG *out_data_len,
                       CK_BYTE  *key_value,
                       CK_BYTE  encrypt)
{
   ICA_DES_VECTOR  empty_iv;
   CK_RV rc;
   unsigned int _out_data_len = *out_data_len;

   memset(&empty_iv, 0, sizeof(empty_iv));
   if ( encrypt) {
      rc = icaDesEncrypt(adapter_handle, (unsigned int)MODE_DES_ECB, (unsigned int)in_data_len, in_data,
                &empty_iv, (ICA_KEY_DES_SINGLE *)key_value, 
                &_out_data_len, out_data);

   } else {
      rc = icaDesDecrypt(adapter_handle, (unsigned int)MODE_DES_ECB, (unsigned int)in_data_len, in_data,
                   &empty_iv, (ICA_KEY_DES_SINGLE *)key_value, 
                   &_out_data_len, out_data);

   }
   if (rc != 0) {
      st_err_log(4, __FILE__, __LINE__, __FUNCTION__);
      rc = CKR_FUNCTION_FAILED;
   }else {
      *out_data_len = in_data_len;
      rc = CKR_OK;
   }

   return rc;


}

CK_RV
token_specific_des_cbc(CK_BYTE * in_data,
                       CK_ULONG in_data_len,
                       CK_BYTE *out_data,
                       CK_ULONG *out_data_len,
                       CK_BYTE  *key_value, 
                       CK_BYTE *init_v,
                       CK_BYTE  encrypt)
{

   CK_RV rc;
   unsigned int _out_data_len = *out_data_len;

   if ( encrypt ){
   rc = icaDesEncrypt(adapter_handle, (unsigned int)MODE_DES_CBC, (unsigned int)in_data_len, in_data,
                            (ICA_DES_VECTOR *)init_v, 
                            (ICA_KEY_DES_SINGLE *)key_value, 
                            &_out_data_len, 
                            (unsigned char *)out_data);
   } else {
   rc = icaDesDecrypt(adapter_handle, (unsigned int)MODE_DES_CBC, (unsigned int)in_data_len, in_data,
                            (ICA_DES_VECTOR *)init_v, 
                            (ICA_KEY_DES_SINGLE *)key_value, 
                            &_out_data_len, 
                            (unsigned char *)out_data);
   }
   if (rc != 0) {
         st_err_log(4, __FILE__, __LINE__, __FUNCTION__);
         rc = CKR_FUNCTION_FAILED;
   }else {
         *out_data_len = in_data_len;
         rc = CKR_OK;
   }

   return rc;
}

CK_RV
token_specific_tdes_ecb(CK_BYTE * in_data,
                       CK_ULONG in_data_len,
                       CK_BYTE *out_data,
                       CK_ULONG *out_data_len,
                       CK_BYTE  *key_value,
                       CK_BYTE  encrypt)
{
   ICA_DES_VECTOR  empty_iv;
   CK_RV rc;
   unsigned int _out_data_len = *out_data_len;
   

   memset(&empty_iv, 0, sizeof(empty_iv));
   if ( encrypt) {
      rc = icaTDesEncrypt(adapter_handle, (unsigned int)MODE_DES_ECB, 
		(unsigned int)in_data_len, in_data,
                &empty_iv, 
                (ICA_KEY_DES_TRIPLE *)key_value, 
                &_out_data_len, out_data);

   } else {
      rc = icaTDesDecrypt(adapter_handle, (unsigned int)MODE_DES_ECB, 
		(unsigned int)in_data_len, in_data,
                &empty_iv, 
                (ICA_KEY_DES_TRIPLE *)key_value, 
                &_out_data_len, out_data);

   }
   if (rc != 0) {
      st_err_log(4, __FILE__, __LINE__, __FUNCTION__);
      rc = CKR_FUNCTION_FAILED;
   }else {
      *out_data_len = in_data_len;
      rc = CKR_OK;
   }

   return rc;


}

CK_RV
token_specific_tdes_cbc(CK_BYTE * in_data,
                       CK_ULONG in_data_len,
                       CK_BYTE *out_data,
                       CK_ULONG *out_data_len,
                       CK_BYTE  *key_value, 
                       CK_BYTE *init_v,
                       CK_BYTE  encrypt)
{

   CK_RV rc;
   unsigned int _out_data_len = *out_data_len;

   if ( encrypt ){
   rc = icaTDesEncrypt((int)adapter_handle, 
			(unsigned int)MODE_DES_CBC, 
			(unsigned int)in_data_len, in_data,
                        (ICA_DES_VECTOR *)init_v, 
                        (ICA_KEY_DES_TRIPLE *)key_value, 
                        &_out_data_len, 
                        (unsigned char *)out_data);
   } else {
   rc = icaTDesDecrypt((int)adapter_handle, (unsigned int)MODE_DES_CBC, 
			    (unsigned int)in_data_len, 
			    in_data,
                            (ICA_DES_VECTOR *)init_v, 
                            (ICA_KEY_DES_TRIPLE *)key_value, 
                            &_out_data_len, 
                            (unsigned char *)out_data);
   }
   if (rc != 0) {
         st_err_log(4, __FILE__, __LINE__, __FUNCTION__);
         rc = CKR_FUNCTION_FAILED;
   }else {
         *out_data_len = in_data_len;
         rc = CKR_OK;
   }

   return rc;
}




#ifndef LITE
#define LITE
#endif
// convert from the local PKCS11 template representation to
// the underlying requirement
// returns the pointer to the local key representation
void *
rsa_convert_public_key( OBJECT    * key_obj )
{
   CK_BBOOL           rc;
   CK_ATTRIBUTE      * modulus = NULL;
   CK_ATTRIBUTE      * pub_exp = NULL;
   ICA_KEY_RSA_MODEXPO *publKey;
   unsigned char       *pkey;
   unsigned int        offset;


   // So we need to generate the publKey in device specific format every time
   // we know the modulus is good, and that the pub_exp is good since

   rc  = template_attribute_find( key_obj->template, CKA_MODULUS,         &modulus );
   rc &= template_attribute_find( key_obj->template, CKA_PUBLIC_EXPONENT, &pub_exp );

   if (rc == FALSE) {
      return NULL;
   }

   publKey = (ICA_KEY_RSA_MODEXPO *) malloc(sizeof(ICA_KEY_RSA_MODEXPO));
   if (publKey == NULL) {
      return NULL;
   }
   memset(publKey, 0, sizeof(ICA_KEY_RSA_MODEXPO));

   // Currently using definition of ICA_KEY_RSA_MODEXPO in NT spec v1.12

   publKey->keyType = KEYTYPE_MODEXPO;
   publKey->keyLength = sizeof(ICA_KEY_RSA_MODEXPO);
   publKey->modulusBitLength = 8 * modulus->ulValueLen;
   publKey->nLength = modulus->ulValueLen;
   publKey->expLength = modulus->ulValueLen;
   offset = (CK_BYTE_PTR) publKey->keyRecord - (CK_BYTE_PTR) publKey;
   publKey->expOffset = offset;
   publKey->nOffset = offset + modulus->ulValueLen;

   pkey = (CK_BYTE_PTR) publKey->keyRecord;
   pkey += modulus->ulValueLen - pub_exp->ulValueLen;
   memcpy(pkey, pub_exp->pValue, pub_exp->ulValueLen);
   pkey += pub_exp->ulValueLen;
   memcpy(pkey, modulus->pValue, modulus->ulValueLen);
   return publKey;

}

void *
rsa_convert_private_key(OBJECT *key_obj)
{
   CK_ATTRIBUTE      * attr     = NULL;
   CK_ATTRIBUTE      * modulus  = NULL;
   CK_ATTRIBUTE      * priv_exp = NULL;
   CK_ATTRIBUTE      * prime1   = NULL;
   CK_ATTRIBUTE      * prime2   = NULL;
   CK_ATTRIBUTE      * exp1     = NULL;
   CK_ATTRIBUTE      * exp2     = NULL;
   CK_ATTRIBUTE      * coeff    = NULL;
   CK_BBOOL          rc;
   CK_BYTE_PTR         pkey;
   ICA_KEY_RSA_CRT     *privKey;
   ICA_KEY_RSA_MODEXPO *privModKey;
   unsigned int        offset, pSize, qSize;

      rc  = template_attribute_find( key_obj->template, CKA_MODULUS,          &modulus );
      rc &= template_attribute_find( key_obj->template, CKA_PRIVATE_EXPONENT, &priv_exp );
      rc &= template_attribute_find( key_obj->template, CKA_PRIME_1,          &prime1 );
      rc &= template_attribute_find( key_obj->template, CKA_PRIME_2,          &prime2 );
      rc &= template_attribute_find( key_obj->template, CKA_EXPONENT_1,       &exp1 );
      rc &= template_attribute_find( key_obj->template, CKA_EXPONENT_2,       &exp2 );
      rc &= template_attribute_find( key_obj->template, CKA_COEFFICIENT,      &coeff );
      if ( !prime2 && !modulus ){
         return NULL;
      }

      // CRT key?
      if ( prime1){
         if (!prime2 || !exp1 ||!exp2 || !coeff) {
            return NULL;
         }
         privKey = (ICA_KEY_RSA_CRT *) malloc(sizeof(ICA_KEY_RSA_CRT));
         if (privKey == NULL) {
            return NULL;
         }
         memset(privKey, 0, sizeof(ICA_KEY_RSA_CRT));

         // Currently using definition of ICA_KEY_RSA_CRT in NT spec v1.12
         // (with nLength and nOffset removed per BEF's e-mail)

         privKey->keyType = KEYTYPE_PKCSCRT;
         privKey->keyLength = sizeof(ICA_KEY_RSA_CRT);
         privKey->modulusBitLength = 8 * modulus->ulValueLen;
         privKey->pLength = prime1->ulValueLen;
         privKey->qLength = prime2->ulValueLen;
         privKey->dpLength = exp1->ulValueLen;
         privKey->dqLength = exp2->ulValueLen;
         privKey->qInvLength = coeff->ulValueLen;
         offset = (CK_BYTE_PTR) privKey->keyRecord
                  - (CK_BYTE_PTR) privKey;
         qSize = modulus->ulValueLen / 2;
         pSize = qSize + 8;   //  1 QWORD larger
         privKey->dpOffset = offset;
         privKey->dqOffset = offset += pSize;
         privKey->pOffset = offset += qSize;
         privKey->qOffset = offset += pSize;
         privKey->qInvOffset = offset + qSize;
         pkey = (CK_BYTE_PTR) privKey->keyRecord;
         pkey += pSize - exp1->ulValueLen;
         memcpy(pkey, exp1->pValue, exp1->ulValueLen);
//       pkey += exp1->ulValueLen + qSize - exp2->ulValueLen;
         pkey += exp1->ulValueLen;
         memcpy(pkey, exp2->pValue, exp2->ulValueLen);
//       pkey += exp2->ulValueLen + pSize - prime1->ulValueLen;
         pkey += qSize + pSize - prime1->ulValueLen;
         memcpy(pkey, prime1->pValue, prime1->ulValueLen);
//       pkey += prime1->ulValueLen + qSize - prime2->ulValueLen;
         pkey += prime1->ulValueLen;
         memcpy(pkey, prime2->pValue, prime2->ulValueLen);
//       pkey += prime2->ulValueLen + pSize - coeff->ulValueLen;
         pkey += qSize + pSize - coeff->ulValueLen;
         memcpy(pkey, coeff->pValue, coeff->ulValueLen);
         return privKey;
//         hex_dump_to_file("PRIVATEKEY",(char *)privKey,sizeof(ICA_KEY_RSA_CRT));
      } else {   // must be a non-CRT key
         if (!priv_exp) {
            return NULL;
         }
         privModKey = (ICA_KEY_RSA_MODEXPO *) malloc(sizeof(ICA_KEY_RSA_MODEXPO));
         if (privModKey == NULL) {
            return NULL;
         }
         memset(privModKey, 0, sizeof(ICA_KEY_RSA_MODEXPO));

         // Currently using definition of ICA_KEY_RSA_MODEXPO in NT spec v1.12

         privModKey->keyType = KEYTYPE_MODEXPO;
         privModKey->keyLength = sizeof(ICA_KEY_RSA_MODEXPO);
         privModKey->modulusBitLength = 8 * modulus->ulValueLen;
         privModKey->nLength = modulus->ulValueLen;
         privModKey->expLength = modulus->ulValueLen;
         offset = (CK_BYTE_PTR) privModKey->keyRecord
                  - (CK_BYTE_PTR) privModKey;
         privModKey->expOffset = offset;
         privModKey->nOffset = offset + modulus->ulValueLen;

         pkey = (CK_BYTE_PTR) privModKey->keyRecord;
         pkey += modulus->ulValueLen - priv_exp->ulValueLen;
         memcpy(pkey, priv_exp->pValue, priv_exp->ulValueLen);
         pkey += priv_exp->ulValueLen;
         memcpy(pkey, modulus->pValue, modulus->ulValueLen);

         return privModKey;
      }
}



//

CK_RV
os_specific_rsa_keygen(TEMPLATE *publ_tmpl,  TEMPLATE *priv_tmpl)
{
   CK_ATTRIBUTE       * publ_exp = NULL;
   CK_ATTRIBUTE       * attr     = NULL;
   CK_BYTE            * ptr      = NULL;
   CK_BYTE              repl_buf[5500];
   CK_ULONG             req_len, repl_len;
   CK_ULONG             mod_bits;
   CK_BBOOL             flag;
   CK_RV                rc;
   CK_BYTE_PTR         pubExp;
   CK_BYTE_PTR         prdat;  // IN format for cryptolite
   CK_BYTE_PTR         pudat;  // IN format for cryptolite
   CK_ULONG            keysize;
   ICA_KEY_RSA_MODEXPO *publKey;
   ICA_KEY_RSA_CRT *privKey;
   unsigned int        offset, len;
   unsigned int        publKeySize, privKeySize;


   flag = template_attribute_find( publ_tmpl, CKA_MODULUS_BITS, &attr );
   if (!flag){
       st_err_log(48, __FILE__, __LINE__);
       return CKR_TEMPLATE_INCOMPLETE;  // should never happen
   }
   mod_bits = *(CK_ULONG *)attr->pValue;

   flag = template_attribute_find( publ_tmpl, CKA_PUBLIC_EXPONENT, &publ_exp );
   if (!flag){
        st_err_log(48, __FILE__, __LINE__);
	return CKR_TEMPLATE_INCOMPLETE;
   }
   //jag
   // we don't support less than 1024 bit keys in the sw
   if (mod_bits < 256 || mod_bits > 2048) {
     st_err_log(19, __FILE__, __LINE__);
     return CKR_KEY_SIZE_RANGE;
   }
    
   if(publ_exp->ulValueLen > (mod_bits * 8)){
     st_err_log(109, __FILE__, __LINE__);
     return CKR_DATA_LEN_RANGE;
   }


   publKey = (ICA_KEY_RSA_MODEXPO *) malloc(sizeof(ICA_KEY_RSA_MODEXPO));
   if (publKey == NULL) {
      st_err_log(1, __FILE__, __LINE__);
      return CKR_HOST_MEMORY;
   }
 

   privKey = (ICA_KEY_RSA_CRT *) malloc(sizeof(ICA_KEY_RSA_CRT));
   if (privKey == NULL) {
     st_err_log(1, __FILE__, __LINE__);
     rc = CKR_HOST_MEMORY;
     goto pubkey_cleanup;
   }


   memset(publKey, 0x00, sizeof(ICA_KEY_RSA_MODEXPO));
   memset(privKey, 0x00, sizeof(ICA_KEY_RSA_CRT)); 

   // Currently using definition of ICA_KEY_RSA_MODEXPO in NT spec v1.12
   
   keysize = ((mod_bits + 7)/8);

   /* Linux driver is not using these */


   ptr = publKey->keyRecord + keysize - publ_exp->ulValueLen;
   memcpy(ptr,publ_exp->pValue, publ_exp->ulValueLen);    

   publKeySize = sizeof(ICA_KEY_RSA_MODEXPO);
   privKeySize = sizeof(ICA_KEY_RSA_CRT);
      
   rc = icaRsaKeyGenerateCrt((int)adapter_handle,
				 (unsigned int)mod_bits,
				 (unsigned int)RSA_PUBLIC_FIXED,
				 &publKeySize,
				 (ICA_KEY_RSA_MODEXPO *)publKey,
				 &privKeySize,
				 (ICA_KEY_RSA_CRT *)privKey);

   
   if(rc){
     st_err_log(4, __FILE__, __LINE__, __FUNCTION__);
     rc = CKR_FUNCTION_FAILED;
     goto privkey_cleanup;
   }
   

   // modulus: n
   //
   ptr = (CK_BYTE *)(publKey->keyRecord + keysize);
   rc = build_attribute( CKA_MODULUS, ptr, keysize, &attr );
   if (rc != CKR_OK){
      st_err_log(84, __FILE__, __LINE__);
      goto privkey_cleanup;
   }
   template_update_attribute( publ_tmpl, attr );

  
   // local = TRUE
   //
   flag = TRUE;
   rc = build_attribute( CKA_LOCAL, &flag, sizeof(CK_BBOOL), &attr );
   if (rc != CKR_OK){
      st_err_log(84, __FILE__, __LINE__);
      goto privkey_cleanup;
   }
   template_update_attribute( publ_tmpl, attr );

   //
   // now, do the private key
   //

   // public exponent: e
   //
   rc = build_attribute( CKA_PUBLIC_EXPONENT, publ_exp->pValue, publ_exp->ulValueLen, &attr );
   if (rc != CKR_OK){
      st_err_log(84, __FILE__, __LINE__);
      goto privkey_cleanup;
   }
   template_update_attribute( priv_tmpl, attr );

   // modulus: n
   //
   ptr = (CK_BYTE *)(publKey->keyRecord + keysize);
   rc = build_attribute( CKA_MODULUS, ptr, keysize, &attr );
   if (rc != CKR_OK){
      st_err_log(84, __FILE__, __LINE__);
      return rc;
   }
   template_update_attribute( priv_tmpl, attr );

   /* CRT sizes are smaller */

   keysize /= 2;

   // exponent 1: d mod(p-1)
   //
   ptr = (CK_BYTE *)(privKey->keyRecord);
   rc = build_attribute( CKA_EXPONENT_1, ptr, keysize + 8, &attr );
   if (rc != CKR_OK){
      st_err_log(84, __FILE__, __LINE__);
      goto privkey_cleanup;
   }
   template_update_attribute( priv_tmpl, attr );

   // exponent 2: d mod(q-1)
   //
   ptr += keysize + 8;
   rc = build_attribute( CKA_EXPONENT_2, ptr, keysize, &attr );
   if (rc != CKR_OK){
      st_err_log(84, __FILE__, __LINE__);
      goto privkey_cleanup;
   }
   template_update_attribute( priv_tmpl, attr );

   // prime #1: p
   //
   ptr += keysize; 
   rc = build_attribute( CKA_PRIME_1, ptr, keysize+8, &attr );
   if (rc != CKR_OK){
      st_err_log(84, __FILE__, __LINE__);
      goto privkey_cleanup;
   }
   template_update_attribute( priv_tmpl, attr );

   
   // prime #2: q
   //
   ptr += keysize + 8;
   rc = build_attribute( CKA_PRIME_2, ptr, keysize, &attr );
   if (rc != CKR_OK){
      st_err_log(84, __FILE__, __LINE__);
      goto privkey_cleanup;
   }
   template_update_attribute( priv_tmpl, attr );


   // CRT coefficient:  q_inverse mod(p)
   //
   ptr += keysize;
   rc = build_attribute( CKA_COEFFICIENT, ptr, keysize + 8, &attr );
   if (rc != CKR_OK){
      st_err_log(84, __FILE__, __LINE__);
      goto privkey_cleanup;
   }
   template_update_attribute( priv_tmpl, attr );

 privkey_cleanup:
   free(privKey);
 pubkey_cleanup:
   free(publKey);
   return rc;

}


// SAB FIXME   this keygen stuff needs to be reworked..
//
//
CK_RV
token_specific_rsa_generate_keypair( TEMPLATE  * publ_tmpl,
                      TEMPLATE  * priv_tmpl )
{
   CK_ATTRIBUTE       * publ_exp = NULL;
   CK_ATTRIBUTE       * attr     = NULL;

   CK_BYTE            * ptr      = NULL;
   CK_BYTE              repl_buf[5500];
   CK_ULONG             req_len, repl_len;
   CK_ULONG             mod_bits;
   CK_BBOOL             flag;
   CK_RV                rc;

   rc = os_specific_rsa_keygen(publ_tmpl,priv_tmpl);
   if (rc != CKR_OK)
         st_err_log(91, __FILE__, __LINE__);
   return rc;
}


//
//
CK_RV
token_specific_rsa_encrypt( CK_BYTE   * in_data,
                 CK_ULONG    in_data_len,
                 CK_BYTE   * out_data,
                 OBJECT    * key_obj )
{
   CK_ATTRIBUTE      * attr    = NULL;
   CK_ATTRIBUTE      * modulus = NULL;
   CK_ATTRIBUTE      * pub_exp = NULL;
   CK_BYTE           * ptr     = NULL;

   CK_ULONG            buffer[80];  // plenty of room...
   CK_OBJECT_CLASS     keyclass;
   CK_ULONG            req_len, repl_len, key_len;
   CK_RV               rc;
   unsigned int        out_data_len;
   ICA_KEY_RSA_MODEXPO *publKey;


   publKey = (ICA_KEY_RSA_MODEXPO *) rsa_convert_public_key(key_obj);
   if (publKey == NULL) {
      st_err_log(4, __FILE__, __LINE__, __FUNCTION__);
      rc = CKR_FUNCTION_FAILED;
      goto done;
   }

   out_data_len = (unsigned int)in_data_len;

   rc = icaRsaModExpo((int)adapter_handle, (unsigned int)in_data_len, in_data,
                      publKey, &out_data_len, out_data);

   if (rc != 0) {
      st_err_log(4, __FILE__, __LINE__, __FUNCTION__);
      rc = CKR_FUNCTION_FAILED;
   } else {
      rc = CKR_OK;
   }
   free(publKey);
   goto done;


done:
   return rc;
}


//
//
CK_RV
token_specific_rsa_decrypt( CK_BYTE   * in_data,
                 CK_ULONG    in_data_len,
                 CK_BYTE   * out_data,
                 OBJECT    * key_obj )
{
   CK_ATTRIBUTE      * attr     = NULL;
   CK_ATTRIBUTE      * modulus  = NULL;
   CK_ATTRIBUTE      * pub_exp  = NULL;
   CK_ATTRIBUTE      * prime1   = NULL;
   CK_ATTRIBUTE      * prime2   = NULL;
   CK_ATTRIBUTE      * exp1     = NULL;
   CK_ATTRIBUTE      * exp2     = NULL;
   CK_ATTRIBUTE      * coeff    = NULL;
   CK_BYTE           * ptr      = NULL;

   CK_ULONG            buffer[80];  // plenty of room...
   CK_OBJECT_CLASS     keyclass;
   CK_ULONG            key_size;
   CK_ULONG            req_len, repl_len;
   CK_RV               rc;

   unsigned int        out_data_len;
   ICA_KEY_RSA_CRT *privKey;


   privKey = (ICA_KEY_RSA_CRT *) rsa_convert_private_key(key_obj);
   if (privKey == NULL) {
      st_err_log(4, __FILE__, __LINE__, __FUNCTION__);
      rc = CKR_FUNCTION_FAILED;
      goto done;
   }

   out_data_len = (unsigned int)in_data_len;

   if (privKey->keyType == KEYTYPE_PKCSCRT) {
      rc = icaRsaCrt((int)adapter_handle, (unsigned int)in_data_len, in_data,
                     privKey, &out_data_len, out_data);
   } else if (privKey->keyType == KEYTYPE_MODEXPO) {
      rc = icaRsaModExpo((int)adapter_handle, (unsigned int)in_data_len, in_data,
           (ICA_KEY_RSA_MODEXPO *) privKey, &out_data_len, out_data);
   } else {
      st_err_log(4, __FILE__, __LINE__, __FUNCTION__);
      rc = CKR_FUNCTION_FAILED;
      free(privKey);
      goto done;
   }

   if (rc != 0) {
      st_err_log(4, __FILE__, __LINE__, __FUNCTION__);
      rc = CKR_FUNCTION_FAILED;
   } else {
      rc = CKR_OK;
   }
   free(privKey);
   goto done;

done:
   return rc;
}



CK_RV
token_specific_session(CK_SLOT_ID  slotid)
{
       return CKR_OK;

}

CK_RV
token_specific_sha_init( DIGEST_CONTEXT * ctx )
{
	oc_sha1_ctx	*sc;

	/* For the C_DigestInit, C_Digest case, we may have already 
	 * created ctx->context... - KEY 
	 */
	if(ctx->context) {
		sc = (oc_sha1_ctx *)ctx->context;
		if(sc->dev_ctx)
			free(sc->dev_ctx);
		free(ctx->context);
	}
	
	/* The caller will check to see if ctx->context == NULL */
	ctx->context_len = sizeof(oc_sha1_ctx);
	ctx->context = malloc(sizeof(oc_sha1_ctx));

	if(ctx->context == NULL) 
		return CKR_HOST_MEMORY;
	
	memset(ctx->context, 0, ctx->context_len);
	sc = (oc_sha1_ctx *)ctx->context;
	sc->hash_len = SHA1_HASH_SIZE;
	sc->message_part = SHA_MSG_PART_ONLY;
	/* This is libica's LENGTH_SHA_CONTEXT */
	sc->dev_ctx = malloc(LENGTH_SHA_CONTEXT);

	if(sc->dev_ctx == NULL){
		free(ctx->context);
		return CKR_HOST_MEMORY;
	}
	memset(sc->dev_ctx, 0, LENGTH_SHA_CONTEXT);
	
	return CKR_OK;
}

CK_RV
token_specific_sha_update(	DIGEST_CONTEXT	*ctx,
				CK_BYTE		*in_data,
				CK_ULONG	in_data_len )
{
	unsigned int	rc, i, fill_size = 0;
	oc_sha1_ctx	*oc_sha_ctx = (oc_sha1_ctx *)ctx->context;
	SHA_CONTEXT	*ica_sha_ctx = (SHA_CONTEXT *)oc_sha_ctx->dev_ctx;
	
	if( !ctx )
		return CKR_OPERATION_NOT_INITIALIZED;
	
	if( !in_data )
		return CKR_FUNCTION_FAILED;
	
	if( ctx->multi == TRUE ){
		if (oc_sha_ctx->tail_len == 64) {
			/* Submit the filled out save buffer */
                        if( icaSha1(    adapter_handle, 
					ica_sha_ctx->runningLength == 0 ? SHA_MSG_PART_FIRST : SHA_MSG_PART_MIDDLE,
					64, oc_sha_ctx->tail,
					LENGTH_SHA_CONTEXT, ica_sha_ctx,
					&oc_sha_ctx->hash_len, oc_sha_ctx->hash))
				return CKR_FUNCTION_FAILED;
			oc_sha_ctx->tail_len = 0;
		}
				
		/* libICA (and SHA1) demands that if this is a PART_FIRST or a 
		 * PART_MIDDLE operation, the amount of data passed in
		 * must be a multiple of 64 bytes. - KEY
		 */
		if( ica_sha_ctx->runningLength == 0 && 
			oc_sha_ctx->tail_len == 0) {
			oc_sha_ctx->message_part = SHA_MSG_PART_FIRST;
		
			/* Just copying the last <64 bytes will not work in the case
			 * of a user who SHA's a large chunk of data in 64 byte
			 * pieces because we need to cache the last 64 bytes so that
			 * we're not stuck with 0 bytes when the MSG_PART_FINAL
			 * comes in. - KEY
			 */
			if (!(in_data_len % 64)) {
				oc_sha_ctx->tail_len = 64;
				memcpy(oc_sha_ctx->tail, in_data + in_data_len - 64, 64);
				in_data_len -= 64;
			} else
				oc_sha_ctx->tail_len = in_data_len & 0x3f;
			
			if(oc_sha_ctx->tail_len < 64) {
				in_data_len &= ~0x3f;	
				memcpy(oc_sha_ctx->tail, in_data + in_data_len, oc_sha_ctx->tail_len);
			}
		}
		else if( ica_sha_ctx->runningLength == 0 &&
				oc_sha_ctx->tail_len > 0 ) {

			/* Here we need to fill out the temporary tail buffer until
			 * it has 64 bytes in it, then call icaSha1 on that buffer.
			 * If there weren't enough bytes passed in to fill it out,
			 * just copy in what we can and return success without calling
			 * icaSha1. - KEY
			 */

			fill_size = 64 - oc_sha_ctx->tail_len;
			if(fill_size < in_data_len) {
				memcpy(oc_sha_ctx->tail + oc_sha_ctx->tail_len, in_data, fill_size);
			
				/* Submit the filled out save buffer */
				if( icaSha1(    adapter_handle, (unsigned int)SHA_MSG_PART_FIRST,
						(unsigned int)64, oc_sha_ctx->tail,
						(unsigned int)LENGTH_SHA_CONTEXT, ica_sha_ctx,
						&oc_sha_ctx->hash_len, oc_sha_ctx->hash))
					return CKR_FUNCTION_FAILED;
			} else {
				memcpy(oc_sha_ctx->tail + oc_sha_ctx->tail_len,
					in_data, in_data_len);
				oc_sha_ctx->tail_len += in_data_len;

				return CKR_OK;
			}
			
                        /* We had to use 'fill_size' bytes from in_data to fill out the
                         * empty part of save data, so adjust in_data_len
                         */
                        in_data_len -= fill_size;

                        oc_sha_ctx->tail_len = in_data_len & 0x3f;
                        if(oc_sha_ctx->tail_len) {
                                memcpy(oc_sha_ctx->tail, 
					in_data + fill_size, 
					oc_sha_ctx->tail_len);
                                in_data_len &= ~0x3f;
                        }
		}
		else if( ica_sha_ctx->runningLength > 0 ) {
			oc_sha_ctx->message_part = SHA_MSG_PART_MIDDLE;

			if(oc_sha_ctx->tail_len) {
	                        fill_size = 64 - oc_sha_ctx->tail_len;
        	                if(fill_size < in_data_len) {
                	                memcpy(oc_sha_ctx->tail + oc_sha_ctx->tail_len, 
							in_data, fill_size);

                        	        /* Submit the filled out save buffer */
                                	if( icaSha1(    adapter_handle, (unsigned int)oc_sha_ctx->message_part,
                                        	        (unsigned int)64, oc_sha_ctx->tail,
                                                	(unsigned int)LENGTH_SHA_CONTEXT, ica_sha_ctx,
	                                                &oc_sha_ctx->hash_len, oc_sha_ctx->hash))
        	                                return CKR_FUNCTION_FAILED;
                	        } else {
                        	        memcpy(oc_sha_ctx->tail + oc_sha_ctx->tail_len,
                                	        in_data, in_data_len);
	                                oc_sha_ctx->tail_len += in_data_len;
	
        	                        return CKR_OK;
                	        }

				/* We had to use some of the data from in_data to fill out the
				 * empty part of save data, so adjust in_data_len
				 */
				in_data_len -= fill_size;
			
				oc_sha_ctx->tail_len = in_data_len & 0x3f;
				if(oc_sha_ctx->tail_len) {
					memcpy(oc_sha_ctx->tail, in_data + fill_size, 
							oc_sha_ctx->tail_len);
					in_data_len &= ~0x3f;	
				}
			} else {
				/* This is the odd case, where we need to go ahead and
				 * send the first X * 64 byte chunks in to be processed
				 * and copy the last <64 byte area into the tail. -KEY
				 */
				/* Just copying the last <64 bytes will not work in the case
				 * of a user who SHA's a large chunk of data in 64 byte
				 * pieces because we need to cache the last 64 bytes so that
				 * we're not stuck with 0 bytes when the MSG_PART_FINAL
				 * comes in. - KEY
				 */
                        	if (!(in_data_len % 64)) {
                                	oc_sha_ctx->tail_len = 64;
	                                memcpy(oc_sha_ctx->tail, in_data + in_data_len - 64, 64);
        	                        in_data_len -= 64;
                	        } else
                        	        oc_sha_ctx->tail_len = in_data_len & 0x3f;

				if( oc_sha_ctx->tail_len < 64) {
					in_data_len &= ~0x3f;
					memcpy(oc_sha_ctx->tail, in_data + in_data_len,
							oc_sha_ctx->tail_len);
				}
			}
		}
	} else {
		/* ctx->multi == FALSE, but we've run previously. That's
		 * our signal that this is the last part -KEY
		 */
		if( ica_sha_ctx->runningLength > 0 )
			oc_sha_ctx->message_part = SHA_MSG_PART_FINAL;
		else
			oc_sha_ctx->message_part = SHA_MSG_PART_ONLY;
	}
	
	if( in_data_len || oc_sha_ctx->message_part == SHA_MSG_PART_FINAL ) {
		if( icaSha1(	adapter_handle, (unsigned int)oc_sha_ctx->message_part,
				(unsigned int)in_data_len, in_data + fill_size,
				(unsigned int)LENGTH_SHA_CONTEXT, ica_sha_ctx,
				&oc_sha_ctx->hash_len, oc_sha_ctx->hash))
			return CKR_FUNCTION_FAILED;
	}
	
	return CKR_OK;
}

CK_RV
token_specific_sha_final(	DIGEST_CONTEXT	*ctx,
				CK_BYTE		*out_data,
				CK_ULONG	*out_data_len )
{
	CK_RV rv = CKR_OK;
	oc_sha1_ctx *oc_sha_ctx = (oc_sha1_ctx *)ctx->context;
	int copy_len = MIN(*out_data_len, LENGTH_SHA_HASH);
	
	if( !ctx )
		return CKR_OPERATION_NOT_INITIALIZED;
	
	if( !out_data || (*out_data_len < LENGTH_SHA_HASH) )
		return CKR_FUNCTION_FAILED;

	if( oc_sha_ctx->message_part != SHA_MSG_PART_FINAL &&
	    oc_sha_ctx->message_part != SHA_MSG_PART_ONLY) {
		/* Finalize the SHA operation; tell update that this multi-part
		 * operation is done. -KEY
		*/
		ctx->multi = FALSE;
		token_specific_sha_update(ctx, oc_sha_ctx->tail, oc_sha_ctx->tail_len);
	}
	
	memcpy(out_data, oc_sha_ctx->hash, copy_len);
	*out_data_len = copy_len;

	/* ctx->context is freed inside digest_mgr_cleanup - KEY */
	free(oc_sha_ctx->dev_ctx);
	return rv;
}

#ifndef NOAES

/* If you'd like openssl AES support, install opensl 0.9.7, edit 
 * usr/lib/pkcs11/ica_stdll/Makefile.am and remove the -DNOAES CFLAG. - KEY
 */

CK_RV
token_specific_aes_key_gen( CK_BYTE *key, CK_ULONG len )
{
        return rng_generate(key, len);
}

CK_RV
token_specific_aes_ecb( CK_BYTE         *in_data,
                        CK_ULONG        in_data_len,
                        CK_BYTE         *out_data,
                        CK_ULONG        *out_data_len,
                        CK_BYTE         *key_value,
                        CK_ULONG        key_len,
                        CK_BYTE         encrypt)
{
        AES_KEY         ssl_aes_key;
        int             i;
        /* There's a previous check that in_data_len % AES_BLOCK_SIZE == 0,
         * so this is fine */
        CK_ULONG        loops = (CK_ULONG)(in_data_len/AES_BLOCK_SIZE);

        memset( &ssl_aes_key, 0, sizeof(AES_KEY));

        // AES_ecb_encrypt encrypts only a single block, so we have to break up the
        // input data here
        if (encrypt) {
                AES_set_encrypt_key((unsigned char *)key_value, (key_len*8), &ssl_aes_key);
                for( i=0; i<loops; i++ ) {
                        AES_ecb_encrypt((unsigned char *)in_data + (i*AES_BLOCK_SIZE),
                                        (unsigned char *)out_data + (i*AES_BLOCK_SIZE),
                                        &ssl_aes_key,
                                        AES_ENCRYPT);
                }
        } else {
                AES_set_decrypt_key((unsigned char *)key_value, (key_len*8), &ssl_aes_key);
                for( i=0; i<loops; i++ ) {
                        AES_ecb_encrypt((unsigned char *)in_data + (i*AES_BLOCK_SIZE),
                                        (unsigned char *)out_data + (i*AES_BLOCK_SIZE),
                                        &ssl_aes_key,
                                        AES_DECRYPT);
                }
        }
        *out_data_len = in_data_len;
        return CKR_OK;
}


CK_RV
token_specific_aes_cbc( CK_BYTE         *in_data,
                        CK_ULONG        in_data_len,
                        CK_BYTE         *out_data,
                        CK_ULONG        *out_data_len,
                        CK_BYTE         *key_value,
                        CK_ULONG        key_len,
                        CK_BYTE         *init_v,
                        CK_BYTE         encrypt)
{
        AES_KEY         ssl_aes_key;
        int             i;

        memset( &ssl_aes_key, 0, sizeof(AES_KEY));

        // AES_cbc_encrypt chunks the data into AES_BLOCK_SIZE blocks, unlike
        // AES_ecb_encrypt, so no looping required.
        if (encrypt) {
                AES_set_encrypt_key((unsigned char *)key_value, (key_len*8), &ssl_aes_key);
                AES_cbc_encrypt((unsigned char *)in_data, (unsigned char *)out_data,
                                in_data_len,              &ssl_aes_key,
                                init_v,                   AES_ENCRYPT);
        } else {
                AES_set_decrypt_key((unsigned char *)key_value, (key_len*8), &ssl_aes_key);
                AES_cbc_encrypt((unsigned char *)in_data, (unsigned char *)out_data,
                                in_data_len,              &ssl_aes_key,
                                init_v,                   AES_DECRYPT);
        }
        *out_data_len = in_data_len;
        return CKR_OK;
}
#endif

#ifndef NODH
// This computes DH shared secret, where:
//     Output: z is computed shared secret
//     Input:  y is other party's public key
//             x is private key
//             p is prime
// All length's are in number of bytes. All data comes in as Big Endian.
 
CK_RV
token_specific_dh_pkcs_derive( CK_BYTE   *z,
                               CK_ULONG  *z_len,
                               CK_BYTE   *y,
                               CK_ULONG  y_len,
                               CK_BYTE   *x,
                               CK_ULONG  x_len,
                               CK_BYTE   *p,
                               CK_ULONG  p_len)
{
     CK_RV  rc ;
     BIGNUM *bn_z, *bn_y, *bn_x, *bn_p ;
     BN_CTX *ctx;
 
     //  Create and Init the BIGNUM structures.
     bn_y = BN_new() ;
     bn_x = BN_new() ;
     bn_p = BN_new() ;
     bn_z = BN_new() ;

     if (bn_z == NULL || bn_p == NULL || bn_x == NULL || bn_y == NULL) {
	     if (bn_y) BN_free(bn_y);
	     if (bn_x) BN_free(bn_x);
	     if (bn_p) BN_free(bn_p);
	     if (bn_z) BN_free(bn_z);
	     st_err_log(1, __FILE__, __LINE__);
	     return CKR_HOST_MEMORY;
     }
     
     BN_init(bn_y) ;
     BN_init(bn_x) ;
     BN_init(bn_p) ;
 
     // Initialize context
     ctx=BN_CTX_new();
     if (ctx == NULL)
     {
        st_err_log(4, __FILE__, __LINE__, __FUNCTION__);
        return CKR_FUNCTION_FAILED;
     }
 
     // Add data into these new BN structures
 
     BN_bin2bn((char *)y, y_len, bn_y);
     BN_bin2bn((char *)x, x_len, bn_x);
     BN_bin2bn((char *)p, p_len, bn_p);
 
     rc = BN_mod_exp(bn_z,bn_y,bn_x,bn_p,ctx);
     if (rc == 0)
     {
        BN_free(bn_z);
        BN_free(bn_y);
        BN_free(bn_x);
        BN_free(bn_p);
        BN_CTX_free(ctx);
 
        st_err_log(4, __FILE__, __LINE__, __FUNCTION__);
        return CKR_FUNCTION_FAILED;
     }
 
     *z_len = BN_num_bytes(bn_z);
     BN_bn2bin(bn_z, z);
 
     BN_free(bn_z);
     BN_free(bn_y);
     BN_free(bn_x);
     BN_free(bn_p);
     BN_CTX_free(ctx);
 
     return CKR_OK;
 
} /* end token_specific_dh_pkcs_derive() */
 
// This computes DH key pair, where:
//     Output: priv_tmpl is generated private key
//             pub_tmpl is computed public key
//     Input:  pub_tmpl is public key (prime and generator)
// All length's are in number of bytes. All data comes in as Big Endian.

CK_RV
token_specific_dh_pkcs_key_pair_gen( TEMPLATE  * publ_tmpl,
                                     TEMPLATE  * priv_tmpl )
{
    CK_BBOOL           rc;
    CK_ATTRIBUTE       *prime_attr = NULL;
    CK_ATTRIBUTE       *base_attr = NULL;
    CK_ATTRIBUTE       *temp_attr = NULL ;
    CK_ATTRIBUTE       *value_bits_attr = NULL;
    CK_BYTE            *temp_byte;
    CK_ULONG           temp_bn_len ;
 
    DH                 *dh ;
    BIGNUM             *bn_p ;
    BIGNUM             *bn_g ;
    BIGNUM             *temp_bn ;
 
    rc  = template_attribute_find( publ_tmpl, CKA_PRIME, &prime_attr );
    rc &= template_attribute_find( publ_tmpl, CKA_BASE, &base_attr );
 
    if (rc == FALSE) {
        st_err_log(4, __FILE__, __LINE__, __FUNCTION__);
        return CKR_FUNCTION_FAILED;
    }
 
    if ((prime_attr->ulValueLen > 256) || (prime_attr->ulValueLen < 64))
    {
        st_err_log(4, __FILE__, __LINE__, __FUNCTION__);
        return CKR_FUNCTION_FAILED;
    }
 
    dh = DH_new() ;
    if (dh == NULL)
    {
        st_err_log(4, __FILE__, __LINE__, __FUNCTION__);
        return CKR_FUNCTION_FAILED;
    }

    // Create and init BIGNUM structs to stick in the DH struct
    bn_p = BN_new();
    bn_g = BN_new();
    if (bn_g == NULL || bn_p == NULL) {
	if (bn_g) BN_free(bn_g);
	if (bn_p) BN_free(bn_p);
	st_err_log(1, __FILE__, __LINE__);
	return CKR_HOST_MEMORY;
    }
    BN_init(bn_p);
    BN_init(bn_g);
 
    // Convert from strings to BIGNUMs and stick them in the DH struct
    BN_bin2bn((char *)prime_attr->pValue, prime_attr->ulValueLen, bn_p);
    dh->p = bn_p;
    BN_bin2bn((char *)base_attr->pValue, base_attr->ulValueLen, bn_g);
    dh->g = bn_g;
 
    // Generate the DH Key
    if (!DH_generate_key(dh))
    {
        st_err_log(4, __FILE__, __LINE__, __FUNCTION__);
        return CKR_FUNCTION_FAILED;
    }
 
    // Extract the public and private key components from the DH struct,
    // and insert them in the publ_tmpl and priv_tmpl
 
    //
    // pub_key
    //
    //temp_bn = BN_new();
    temp_bn = dh->pub_key;
    temp_bn_len = BN_num_bytes(temp_bn);
    temp_byte = malloc(temp_bn_len);
    temp_bn_len = BN_bn2bin(temp_bn, temp_byte);
    rc = build_attribute( CKA_VALUE, temp_byte, temp_bn_len, &temp_attr ); // in bytes
    if (rc != CKR_OK)
    {
        st_err_log(84, __FILE__, __LINE__);
        return CKR_FUNCTION_FAILED;
    }
    template_update_attribute( publ_tmpl, temp_attr );
    free(temp_byte);

    //
    // priv_key
    //
    //temp_bn = BN_new();
    temp_bn = dh->priv_key;
    temp_bn_len = BN_num_bytes(temp_bn);
    temp_byte = malloc(temp_bn_len);
    temp_bn_len = BN_bn2bin(temp_bn, temp_byte);
    rc = build_attribute( CKA_VALUE, temp_byte, temp_bn_len, &temp_attr ); // in bytes
    if (rc != CKR_OK)
    {
        st_err_log(84, __FILE__, __LINE__);
        return CKR_FUNCTION_FAILED;
    }
    template_update_attribute( priv_tmpl, temp_attr );
    free(temp_byte);
 
    // Update CKA_VALUE_BITS attribute in the private key
    value_bits_attr = (CK_ATTRIBUTE *)malloc( sizeof(CK_ATTRIBUTE) + sizeof(CK_ULONG) );
    value_bits_attr->type       = CKA_VALUE_BITS;
    value_bits_attr->ulValueLen = sizeof(CK_ULONG);
    value_bits_attr->pValue     = (CK_BYTE *)value_bits_attr + sizeof(CK_ATTRIBUTE);
    *(CK_ULONG *)value_bits_attr->pValue = 8*temp_bn_len;
    template_update_attribute( priv_tmpl, value_bits_attr );
 
    // Add prime and base to the private key template
    rc = build_attribute( CKA_PRIME,(char *)prime_attr->pValue,
                          prime_attr->ulValueLen, &temp_attr ); // in bytes
    if (rc != CKR_OK)
    {
        st_err_log(84, __FILE__, __LINE__);
        return CKR_FUNCTION_FAILED;
    }
    template_update_attribute( priv_tmpl, temp_attr );
 
    rc = build_attribute( CKA_BASE,(char *)base_attr->pValue,
                          base_attr->ulValueLen, &temp_attr ); // in bytes
    if (rc != CKR_OK)
    {
        st_err_log(84, __FILE__, __LINE__);
        return CKR_FUNCTION_FAILED;
    }
    template_update_attribute( priv_tmpl, temp_attr );

    // Cleanup DH key
    DH_free(dh) ;
 
    return CKR_OK ;
 
} /* end token_specific_dh_key_pair_gen() */
#endif /* #ifndef NODH */

MECH_LIST_ELEMENT mech_list[] = {
   { CKM_RSA_PKCS_KEY_PAIR_GEN,     512, 2048, CKF_HW | CKF_GENERATE_KEY_PAIR },
#if !(NODSA)
   { CKM_DSA_KEY_PAIR_GEN,          512, 1024, CKF_HW | CKF_GENERATE_KEY_PAIR },
#endif
   { CKM_DES_KEY_GEN,                 8,    8, CKF_HW | CKF_GENERATE },
   { CKM_DES3_KEY_GEN,                24,    24, CKF_HW | CKF_GENERATE },
#if !(NOCDMF)
   { CKM_CDMF_KEY_GEN,                0,    0, CKF_HW | CKF_GENERATE },
#endif

   { CKM_RSA_PKCS,                  512, 2048, CKF_HW           |
                                               CKF_ENCRYPT      | CKF_DECRYPT |
                                               CKF_WRAP         | CKF_UNWRAP  |
                                               CKF_SIGN         | CKF_VERIFY  |
                                               CKF_SIGN_RECOVER | CKF_VERIFY_RECOVER },
#if !(NOX509)
   { CKM_RSA_X_509,                 512, 2048, CKF_HW           |
                                               CKF_ENCRYPT      | CKF_DECRYPT |
                                               CKF_WRAP         | CKF_UNWRAP  |
                                               CKF_SIGN         | CKF_VERIFY  |
                                               CKF_SIGN_RECOVER | CKF_VERIFY_RECOVER },
#endif
#if !(NOMD2)
   { CKM_MD2_RSA_PKCS,              512, 2048, CKF_HW      |
                                               CKF_SIGN    | CKF_VERIFY },

#endif
#if !(NOMD5)
   { CKM_MD5_RSA_PKCS,              512, 2048, CKF_HW      |
                                               CKF_SIGN    | CKF_VERIFY },
#endif
#if !(NOSHA1)
   { CKM_SHA1_RSA_PKCS,             512, 2048, CKF_HW      |
                                               CKF_SIGN    | CKF_VERIFY },
#endif


#if !(NODSA)
   { CKM_DSA,                       512, 1024, CKF_HW      |
                                               CKF_SIGN    | CKF_VERIFY },
#endif

/* Begin code contributed by Corrent corp. */
#if !(NODH)
   { CKM_DH_PKCS_DERIVE,            512, 2048, CKF_HW | CKF_DERIVE },
   { CKM_DH_PKCS_KEY_PAIR_GEN,      512, 2048, CKF_HW | CKF_GENERATE_KEY_PAIR },
#endif
/* End code contributed by Corrent corp. */

   { CKM_DES_ECB,                     8,    8, CKF_HW      |
                                               CKF_ENCRYPT | CKF_DECRYPT |
                                               CKF_WRAP    | CKF_UNWRAP },

   { CKM_DES_CBC,                     8,    8, CKF_HW      |
                                               CKF_ENCRYPT | CKF_DECRYPT |
                                               CKF_WRAP    | CKF_UNWRAP },

   { CKM_DES_CBC_PAD,                 8,    8, CKF_HW      |
                                               CKF_ENCRYPT | CKF_DECRYPT |
                                               CKF_WRAP    | CKF_UNWRAP },

#if !(NOCDMF)
   { CKM_CDMF_ECB,                    0,    0, CKF_HW      |
                                               CKF_ENCRYPT | CKF_DECRYPT |
                                               CKF_WRAP    | CKF_UNWRAP },

   { CKM_CDMF_CBC,                    0,    0, CKF_HW      |
                                               CKF_ENCRYPT | CKF_DECRYPT |
                                               CKF_WRAP    | CKF_UNWRAP },
#endif

   { CKM_DES3_ECB,                    24,    24, CKF_HW      |
                                               CKF_ENCRYPT | CKF_DECRYPT |
                                               CKF_WRAP    | CKF_UNWRAP },

   { CKM_DES3_CBC,                    24,    24, CKF_HW      |
                                               CKF_ENCRYPT | CKF_DECRYPT |
                                               CKF_WRAP    | CKF_UNWRAP },

   { CKM_DES3_CBC_PAD,                24,    24, CKF_HW      |
                                               CKF_ENCRYPT | CKF_DECRYPT |
                                               CKF_WRAP    | CKF_UNWRAP },

#if !(NOSHA1)
   { CKM_SHA_1,                       0,    0, CKF_HW | CKF_DIGEST },
   { CKM_SHA_1_HMAC,                  0,    0, CKF_HW | CKF_SIGN | CKF_VERIFY },
   { CKM_SHA_1_HMAC_GENERAL,          0,    0, CKF_HW | CKF_SIGN | CKF_VERIFY },
   { CKM_SHA256,                       0,    0, CKF_HW | CKF_DIGEST },
   { CKM_SHA256_HMAC,                  0,    0, CKF_HW | CKF_SIGN | CKF_VERIFY },
   { CKM_SHA256_HMAC_GENERAL,          0,    0, CKF_HW | CKF_SIGN | CKF_VERIFY },
#endif

#if !(NOMD2)
   { CKM_MD2,                         0,    0, CKF_HW | CKF_DIGEST },
   { CKM_MD2_HMAC,                    0,    0, CKF_HW | CKF_SIGN | CKF_VERIFY },
   { CKM_MD2_HMAC_GENERAL,            0,    0, CKF_HW | CKF_SIGN | CKF_VERIFY },
#endif

#if !(NOMD5)
   { CKM_MD5,                         0,    0, CKF_HW | CKF_DIGEST },
   { CKM_MD5_HMAC,                    0,    0, CKF_HW | CKF_SIGN | CKF_VERIFY },
   { CKM_MD5_HMAC_GENERAL,            0,    0, CKF_HW | CKF_SIGN | CKF_VERIFY },
#endif

   { CKM_SSL3_PRE_MASTER_KEY_GEN,    48,   48, CKF_HW | CKF_GENERATE },
   { CKM_SSL3_MASTER_KEY_DERIVE,     48,   48, CKF_HW | CKF_DERIVE },
   { CKM_SSL3_KEY_AND_MAC_DERIVE,    48,   48, CKF_HW | CKF_DERIVE },
   { CKM_SSL3_MD5_MAC,              384,  384, CKF_HW | CKF_SIGN | CKF_VERIFY },
   { CKM_SSL3_SHA1_MAC,             384,  384, CKF_HW | CKF_SIGN | CKF_VERIFY },

#if !(NOAES)
   { CKM_AES_KEY_GEN,                16,   32, CKF_HW },
   { CKM_AES_ECB,                    16,   32, CKF_HW      |
   					       CKF_ENCRYPT | CKF_DECRYPT |
   					       CKF_WRAP    | CKF_UNWRAP },
   { CKM_AES_CBC,                    16,   32, CKF_HW      |
   					       CKF_ENCRYPT | CKF_DECRYPT |
   					       CKF_WRAP    | CKF_UNWRAP },
   { CKM_AES_MAC,                    16,   32, CKF_HW | CKF_SIGN | CKF_VERIFY },
   { CKM_AES_MAC_GENERAL,            16,   32, CKF_HW | CKF_SIGN | CKF_VERIFY },
   { CKM_AES_CBC_PAD,                16,   32, CKF_HW      |
   					       CKF_ENCRYPT | CKF_DECRYPT |
   					       CKF_WRAP    | CKF_UNWRAP },
#endif
	
#if !(NORIPE)
   { CKM_RIPEMD128,			0,   0, CKF_HW | CKF_DIGEST },
   { CKM_RIPEMD128_HMAC,		0,   0, CKF_HW | CKF_SIGN | CKF_VERIFY },
   { CKM_RIPEMD128_HMAC_GENERAL,	0,   0, CKF_HW | CKF_SIGN | CKF_VERIFY },
   { CKM_RIPEMD160,			0,   0, CKF_HW | CKF_DIGEST },
   { CKM_RIPEMD160_HMAC,		0,   0, CKF_HW | CKF_SIGN | CKF_VERIFY },
   { CKM_RIPEMD160_HMAC_GENERAL,	0,   0, CKF_HW | CKF_SIGN | CKF_VERIFY },
#endif
   
};

CK_ULONG mech_list_len = (sizeof(mech_list) / sizeof(MECH_LIST_ELEMENT));

CK_RV
token_specific_get_mechanism_list(CK_MECHANISM_TYPE_PTR pMechanismList,
				  CK_ULONG_PTR pulCount)
{
	int rc;
	/* common/mech_list.c */
	rc = ock_generic_get_mechanism_list(pMechanismList, pulCount);
	return rc;
}

CK_RV
token_specific_get_mechanism_info(CK_MECHANISM_TYPE type, 
				  CK_MECHANISM_INFO_PTR pInfo)
{
	int rc;
	/* common/mech_list.c */
	rc = ock_generic_get_mechanism_info(type, pInfo);
	return rc;
}
