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

CSSM_CSP_HANDLE cspHandle;
#define CSSM_ERROR      CSSM_GetError()->error


uint32
JnhCryptoInitialize(void) 
{
  CSSM_VERSION          version = { CSSM_MAJOR, CSSM_MINOR };
  CSSM_MEMORY_FUNCS     memoryFuncs = { CR_CSSM_Malloc, CR_CSSM_Free, 
                                        CR_CSSM_Realloc, CR_CSSM_Calloc, 
                                        NULL };
  CSSM_LIST             *moduleListPtr = NULL; 
  CSSM_MODULE_INFO      *moduleInfoPtr = NULL;
  CSSM_VERSION          cspVersion = {1,0};
  CSSM_GUID             IBM_CYLINK_CSP_GUID = { 0xba047041, 0x31f4, 0x11d2, 
                                                { 0xb1, 0xd4, 0x0, 0x20, 0x35,
                                                  0x68, 0xb, 0x0 } };
  CSSM_GUID             IBM_BSAFE_CSP_GUID  = { 0xdda0c1e0, 0x7b73, 0x11d0, 
                                                { 0x8e, 0x0c, 0x0, 0x04, 0xac,
                                                  0x60, 0x2b, 0x18 } };
  uint32 status;

  if (CSSM_Init(&version, &memoryFuncs, NULL)) {
    return CSSM_ERROR;
  }
  if (!(moduleListPtr = CSSM_ListModules(CSSM_SERVICE_CSP, CSSM_FALSE))) {
    return CSSM_ERROR;
  }
#if 0
  // assume there is only one CSP addin module installed
  if (!(moduleInfoPtr = CSSM_GetModuleInfo(&(moduleListPtr->Items[0].GUID),
                                           CSSM_SERVICE_CSP,
                                           CSSM_ALL_SUBSERVICES,
                                           CSSM_INFO_LEVEL_ALL_ATTR))) {
    return CSSM_ERROR;
  }
#endif
  if (!(cspHandle = CSSM_ModuleAttach(&IBM_BSAFE_CSP_GUID, &cspVersion, 
                                      &memoryFuncs, 0, 0, 0, NULL, NULL))) {
	  status = CSSM_ERROR;
    return CSSM_ERROR;
  }
  if (moduleInfoPtr) {
    if (CSSM_FreeModuleInfo(moduleInfoPtr) == CSSM_FAIL) {
      return CSSM_ERROR;
    }
  }
  if (moduleListPtr) {
    if (CSSM_FreeList(moduleListPtr) == CSSM_FAIL) {
      return CSSM_ERROR;
    }
  }
  return 0;
}

uint32
CR_SHA1(const CSSM_DATA_PTR in, CSSM_DATA &out)
{
  uint32                status;
  CSSM_CC_HANDLE        ccHandle;

  if (!(ccHandle = CSSM_CSP_CreateDigestContext(cspHandle, CSSM_ALGID_SHA1))) {
    return CSSM_ERROR;
  }
  out.Data = NULL;
  out.Length = 0;
  if (CSSM_DigestData(ccHandle, in, 1, &out)) {
    status = CSSM_ERROR;
  } else {
    status = 0;
  }
  CSSM_DeleteContext(ccHandle);
  return status;
}


uint32
CR_GenerateRSAKey(uint32 keysize, CSSM_KEY &publicKey, CSSM_KEY &privateKey)
{
  CSSM_CC_HANDLE        ccHandle;
  uint32                keyUsage;
  uint32                keyAttr;
  uint32                status;


   keyUsage = (CSSM_KEYUSE_SIGN | CSSM_KEYUSE_VERIFY | CSSM_KEYUSE_ENCRYPT |
               CSSM_KEYUSE_DECRYPT);
   keyAttr = CSSM_KEYATTR_PERMANENT;

   if (!(ccHandle = CSSM_CSP_CreateKeyGenContext(cspHandle, CSSM_ALGID_RSA,
                                                 NULL, keysize, NULL, NULL, 
                                                 NULL, NULL, NULL))) {
     return CSSM_ERROR;
     
   }
   memset(&publicKey, 0, sizeof(CSSM_KEY));
   memset(&privateKey, 0, sizeof(CSSM_KEY));
   if (CSSM_GenerateKeyPair(ccHandle, keyUsage, keyAttr, NULL, &publicKey, 
                            keyUsage, keyAttr, NULL, &privateKey)) {
     status = CSSM_ERROR;
   } else {
     status = 0;
   }
   CSSM_DeleteContext(ccHandle);
   return status;
}


uint32
CR_RSASignWithSHA1(CSSM_KEY key, const CSSM_DATA_PTR data, 
                   CSSM_DATA &signature)
{
  CSSM_CC_HANDLE        ccHandle;
  uint32                status;

  if (!(ccHandle = CSSM_CSP_CreateSignatureContext(cspHandle, 
                                                   CSSM_ALGID_SHA1WithRSA, 
                                                   NULL, &key))) {
    return CSSM_ERROR;
  }
  signature.Data = 0;
  signature.Length = 0;
  if (CSSM_SignData(ccHandle, data, 1, &signature)) {
    status = CSSM_ERROR;
  } else {
    status = 0;
  }
  CSSM_DeleteContext(ccHandle);
  return status;
}

uint32
CR_SHA1WithRSAVerify(CSSM_KEY key, const CSSM_DATA_PTR data,
                     const CSSM_DATA_PTR signature, bool &isVerified)
{
  CSSM_CC_HANDLE        ccHandle;

  if (!(ccHandle = CSSM_CSP_CreateSignatureContext(cspHandle, 
                                                   CSSM_ALGID_SHA1WithRSA, 
                                                   NULL, &key))) {
    return CSSM_ERROR;
  }
  isVerified = CSSM_VerifyData(ccHandle, data, 1, signature);
  CSSM_DeleteContext(ccHandle);
  return 0;
}

uint32
CR_HMACWithSHA1(const CSSM_DATA_PTR data, CSSM_KEY key, CSSM_DATA &mac)
{
#if 0
  char		ipad = 0x36;		// defined in RFC2104
  char		opad = 0x5c;		// defined in RFC2104
  unsigned int	counter = 0;		// loop counter
  unsigned int	B = 0;			// block size (bytes)
  unsigned int	L = 0;			// hash output size (bytes)
  unsigned char	*keypad = NULL;		// padded key storage
  unsigned char	*innerKey;		// key xor with ipad
  unsigned char	*outerKey;		// key xor with opad
  unsigned char	*inner;			// inner hash
  unsigned int	innerLen;		// inner hash len
  unsigned char	*outer;			// outer hash
  unsigned int	outerLen;		// outer hash len
  unsigned char	*in;			// Input to hashp
  unsigned char	*tp;			// temp pointer
  unsigned char *keydata = key.KeyData.data;
  unsigned int	keylen = key.KeyData.Length;

  do {
    if (keylen > B) {
      if ((status = CR_SHA1(key, &keypad, &i))) {
	break;
      }
    } else {
      if ((keypad = (unsigned char *) malloc(B)) == NULL) {
	throw "out of memory in CR_HMACWithSHA1";
      }
      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 + datalen)) == NULL) {
      throw "out of memory in CR_HMACWithSHA1";
    }
    memcpy(in, innerKey, B);
    tp = in + B;
    memcpy(tp, data, datalen);
    if ((status = sha1(in, B + datalen, &inner, &innerLen))) {
      break;
    }
    memset(in, 0, B + datalen);
    free(in);
    if ((in = (unsigned char *) malloc(B + innerLen)) == NULL) {
      return -1;
    }
    memcpy(in, outerKey, B);
    tp = in + B;
    memcpy(tp, inner, innerLen);
    if ((status = sha1(in, B+innerLen, &outer, &outerLen))) {
      break;
    }
  } while(0);
  mac.Data = outer;
  mac.Len = outerLen;
  if (in) {
    memset(in, 0, B + innerLen);
    free(in);
    in = NULL;
  }
  if (outerKey) {
    memset(outerKey, 0, B);
    free(outerKey);
  }
  if (innerKey) {
    memset(innerKey, 0, B);
    free(innerKey);
  }
#endif
  return 0;
}

