/* ***************************************************************** *
 * Copyright 1998 International Business Machines Corporation. All   *
 * Rights Reserved.                                                  *
 *                                                                   *
 * Please read this carefully.  Your use of this reference           *
 * implementation of certain of the IETF public-key infrastructure   *
 * specifications ("Software") indicates your acceptance of the      *
 * following.  If you do not agree to the following, do not install  *
 * or use any of the Software.                                       *
 *                                                                   *
 * Permission to use, reproduce, distribute and create derivative    *
 * works from the Software ("Software Derivative Works"), and to     *
 * distribute such Software Derivative Works is hereby granted to    *
 * you by International Business Machines Corporation ("IBM").  This *
 * permission includes a license under the patents of IBM that are   *
 * necessarily infringed by your use of the Software as provided by  *
 * IBM.                                                              *
 *                                                                   *
 * IBM licenses the Software to you on an "AS IS" basis, without     *
 * warranty of any kind.  IBM HEREBY EXPRESSLY DISCLAIMS ALL         *
 * WARRANTIES OR CONDITIONS, EITHER EXPRESS OR IMPLIED, INCLUDING,   *
 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OR CONDITIONS OF       *
 * MERCHANTABILITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR    *
 * PURPOSE.  You are solely responsible for determining the          *
 * appropriateness of using this Software and assume all risks       *
 * associated with the use of this Software, including but not       *
 * limited to the risks of program errors, damage to or loss of      *
 * data, programs or equipment, and unavailability or interruption   *
 * of operations.                                                    *
 *                                                                   *
 * IBM WILL NOT BE LIABLE FOR ANY DIRECT DAMAGES OR FOR ANY SPECIAL, *
 * INCIDENTAL, OR  INDIRECT DAMAGES OR FOR ANY ECONOMIC              *
 * CONSEQUENTIAL DAMAGES (INCLUDING LOST PROFITS OR SAVINGS), EVEN   *
 * IF IBM HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.  IBM  *
 * will not be liable for the loss of, or damage to, your records or *
 * data, or any damages claimed by you based on a third party claim. *
 *                                                                   *
 * IBM wishes to obtain your feedback to assist in improving the     *
 * Software.  You grant IBM a world-wide, royalty-free right to use, *
 * copy, distribute, sublicense and prepare derivative works based   *
 * upon any feedback, including materials, error corrections,        *
 * Software Derivatives, enhancements, suggestions and the like that *
 * you provide to IBM relating to the Software (this does not        *
 * include products for which you charge a royalty and distribute to *
 * IBM under other terms and conditions).                            *
 *                                                                   *
 * You agree to distribute the Software and any Software Derivatives *
 * under a license agreement that: 1) is sufficient to notify all    *
 * licensees of the Software and Software Derivatives that IBM       *
 * assumes no liability for any claim that may arise regarding the   *
 * Software or Software Derivatives, and 2) that disclaims all       *
 * warranties, both express and implied, from IBM regarding the      *
 * Software and Software Derivatives.  (If you include this          *
 * Agreement with any distribution of the Software or Software       *
 * Derivatives you will have met this requirement.)  You agree that  *
 * you will not delete any copyright notices in the Software.        *
 *                                                                   *
 * This Agreement is the exclusive statement of your rights in the   *
 * Software as provided by IBM.   Except for the rights granted to   *
 * you in the second paragraph above, You are not granted any other  *
 * patent rights, including but not limited to the right to make     *
 * combinations of the Software with products that infringe IBM      *
 * patents. You agree to comply with all applicable laws and         *
 * regulations, including all export and import laws and regulation. *
 * This Agreement is governed by the laws of the State of New York.  *
 * This Agreement supersedes all other communications,               *
 * understandings or agreements we may have had prior to this        *
 * Agreement.                                                        *
 * ***************************************************************** */

#include <cssm.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <crypto.h>
#include <CdsaMem.h>
#include <jkl.h>

static  CSSM_CSP_HANDLE hmacCspHandle = NULL;
static uint32
sha1(const r_buffer_t in, buffer_t &out)
{
  CSSM_ALGORITHMS       alg = CSSM_ALGID_SHA1;
  CSSM_GUID             cylinkGUID = *JKL_Get_CylinkCsp_GUID();
  uint32                status = 0;
  CSSM_DATA             cin;
  asn_octetstring       cout;
  unsigned char         *tp;
  uint32                tl;
  
  do {
    if (hmacCspHandle == NULL) {
      if ((status = JKL_AttachCSP(cylinkGUID, hmacCspHandle)) != 0) {
        break;
      }
    }
    cin.Data = in.data;
    cin.Length = in.data_len;
    if ((status = JKL_DigestData(hmacCspHandle, alg, cin, cout))) {
      break;
    }
    if ((status = cout.get_value(tp, tl))) {
      break;
    }
  } while(0);
  if (!status) {
    out.clear();
    status = out.append(tp, tl);
  }
  return status;
}
  
uint32
CR_HMACWithSHA1(buffer_t &data, buffer_t &key,  buffer_t &mac)
{
  char          ipad = 0x36;            // defined in RFC2104
  char          opad = 0x5c;            // defined in RFC2104
  r_buffer_t    hashIn;                 // input to hash function
  buffer_t      hashOut;                // output to hash function
  buffer_t      inner;                  // inner hash
  buffer_t      outer;                  // outer hash
  unsigned int  B = 64;                 // block size (bytes)
  unsigned int  L = 20;                 // hash output size (bytes)
  unsigned char *keypad = NULL;         // padded key storage
  unsigned char *innerKey = NULL;       // key xor with ipad
  unsigned char *outerKey = NULL;       // key xor with opad
  unsigned char *in = NULL;             // Input to hashp
  unsigned char *tp = NULL;             // temp pointer
  unsigned char *keydata = key.data;
  uint32        keylen = key.data_len;
  uint32        status;
  uint32        i;

  do {
    if ((keypad = (unsigned char *) malloc(B)) == NULL) {
      throw "out of memory in CR_HMACWithSHA1";
    }
    if (keylen > B) {
      if ((status = sha1(key, hashOut))) {
        break;
      }
      memset(keypad, 0, B);
      memcpy(keypad, hashOut.data, hashOut.data_len);
      hashOut.clear();
    } else {
      memset(keypad, 0, B);
      memcpy(keypad, keydata, keylen);
    }
    if ((innerKey = (unsigned char *) malloc(B)) == NULL) {
      throw "out of memory in CR_HMACWithSHA1";    
    }
    if ((outerKey = (unsigned char *) malloc(B)) == NULL) {
      throw "out of memory in CR_HMACWithSHA1";
    }
    memset(innerKey, 0, B);
    memset(outerKey, 0, B);
    for(i = 0; i < B; i++) {
      innerKey[i] = keypad[i] ^ ipad;
      outerKey[i] = keypad[i] ^ opad;
    }
    memset(keypad, 0, B);
    free(keypad);
    if ((in = (unsigned char *) malloc(B + data.data_len)) == NULL) {
      throw "out of memory in CR_HMACWithSHA1";
    }
    memcpy(in, innerKey, B);
    tp = in + B;
    memcpy(tp, data.data, data.data_len);
    hashIn.data = in;
    hashIn.data_len = B + data.data_len;
    if ((status = sha1(hashIn, inner))) {
      break;
    }
    memset(in, 0, B + data.data_len);
    free(in);
    if ((in = (unsigned char *) malloc(B + inner.data_len)) == NULL) {
      throw "out of memory in CR_HMACWithSHA1";
    }
    memcpy(in, outerKey, B);
    tp = in + B;
    memcpy(tp, inner.data, inner.data_len);
    hashIn.data = in;
    hashIn.data_len = B + inner.data_len;
    if ((status = sha1(hashIn, outer))) {
      break;
    }
  } while(0);
  if (!status) {
    mac.clear();
    mac.append(outer.data, outer.data_len);
  }
  inner.clear();
  outer.clear();
  if (in) {
    free(in);
    in = NULL;
  }
  if (outerKey) {
    memset(outerKey, 0, B);
    free(outerKey);
  }
  if (innerKey) {
    memset(innerKey, 0, B);
    free(innerKey);
  }
  return status;
}

