/* ***************************************************************** *
 * 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 "pkcsprivate.h"

extern CSSM_SPI_MEMORY_FUNCS CssmMemFuncs;



/*****************************************************************************
 * Function: GenerateMac 
 * 
 * Generate message authentication code of passed data.
 *
 * Input:
 *  CssmCSPHandle   - CSP session handle  
 *  CssmCCHandle    - Context handle
 *  pCssmContext    - Pointer to context 
 *  pCssmDataBufs   - Data to be mac'ed
 *  CssmDataBufCount  - Number of input buffers
 *   
 * Output:
 *  pCssmMac      - Computed mac
 *   
 * Returns:
 *  CSSM_OK       - Successful      
 *  CSSM_FAIL     - Failed
 *
 */

CSSM_RETURN CSSMAPI GenerateMac(
  CSSM_CSP_HANDLE CssmCSPHandle,
  CSSM_CC_HANDLE CssmCCHandle,
  const CSSM_CONTEXT_PTR pCssmContext,
  const CSSM_DATA_PTR pCssmDataBufs,
  uint32 CssmDataBufCount,
  CSSM_DATA_PTR pCssmMac)
{
  int CssmRc = CSSM_OK;

  if ((CssmRc = GenerateMacInit(CssmCSPHandle, CssmCCHandle, pCssmContext)) != CSSM_OK)
    return CssmRc;
  
  if ((CssmRc = GenerateMacUpdate(CssmCSPHandle, CssmCCHandle, pCssmDataBufs, CssmDataBufCount)) != CSSM_OK)
    return CssmRc;

  CssmRc =  GenerateMacFinal(CssmCSPHandle, CssmCCHandle, pCssmMac);
  return CssmRc;
}



/*****************************************************************************
 * Function: GenerateMacInit
 *
 * Init stage of mac operation.
 *
 * Input:
 *  CssmCSPHandle   - CSP session handle  
 *  CssmCCHandle    - Context handle
 *  pCssmContext    - Pointer to context 
 *   
 * Output:
 *  None
 *   
 * Returns:
 *  CSSM_OK       - Successful      
 *  CSSM_FAIL     - Failed
 *
 */

CSSM_RETURN CSSMAPI GenerateMacInit(
  CSSM_CSP_HANDLE CssmCSPHandle,
  CSSM_CC_HANDLE CssmCCHandle,
  const CSSM_CONTEXT_PTR pCssmContext)
{

  CSSM_CONTEXT_ATTRIBUTE_PTR  pCssmKeyAttr;
  CSSM_CONTEXT_ATTRIBUTE_PTR  pCssmEffectiveKeyBitsAttr = NULL;
  CSSM_CONTEXT_ATTRIBUTE_PTR  pCssmWordSizeAttr = NULL;
  CSSM_CONTEXT_ATTRIBUTE_PTR  pCssmRoundsAttr = NULL;
  CSSM_CONTEXT_ATTRIBUTE_PTR  pCssmOutputSizeAttr = NULL;


  CSSM_KEY_PTR        pCssmKey;


  CK_RV           PkcsStatus;
  CK_MECHANISM        PkcsMechanism = {0, NULL_PTR, 0};
  CK_OBJECT_HANDLE      hPkcsKey;
#ifdef PKCS11_V20
  CK_RC2_PARAMS       PkcsRc2Params;
#else
  CK_USHORT         PkcsRc2Params;
#endif

#ifdef PKCS11_V20
  CK_RC5_PARAMS       PkcsRc5Params;
  CK_MAC_GENERAL_PARAMS   PkcsMacGeneralParams;
#endif


  MSMSESSION_PTR        pMsmSession;
  


  if ((pMsmSession = FindMsmSession(CssmCSPHandle)) == NULL)
    return SetErr(CSSM_CSP_INVALID_CSP_HANDLE);

  if (pCssmContext->ContextType != CSSM_ALGCLASS_MAC)
    return SetErr(CSSM_CSP_INVALID_CONTEXT);

  // Setting things up for init

  switch (pCssmContext->AlgorithmType)
  {
#ifdef PKCS11_V20
    case CSSM_ALGID_RC5:
      pCssmWordSizeAttr = CSSM_GetContextAttribute(pCssmContext, CSSM_ATTRIBUTE_BLOCK_SIZE);
      if (pCssmWordSizeAttr == NULL)
        return SetErr(CSSM_CSP_PARAM_NO_PARAM);   
        //return SetErr(CSSM_CSP_PARAM_NO_BLOCK_SIZE);    

      pCssmRoundsAttr = CSSM_GetContextAttribute(pCssmContext, CSSM_ATTRIBUTE_ROUNDS);
      if (pCssmRoundsAttr == NULL)
        return SetErr(CSSM_CSP_PARAM_NO_ROUNDS);

      PkcsMechanism.mechanism = CKM_RC5_MAC;
      PkcsRc5Params.ulWordsize = pCssmWordSizeAttr->Attribute.Uint32; 
      PkcsRc5Params.ulRounds = pCssmRoundsAttr->Attribute.Uint32;   
      PkcsMechanism.pParameter = &PkcsRc5Params;
      PkcsMechanism.ulParameterLen = sizeof(PkcsRc5Params);

      break;

    case CSSM_ALGID_CAST:
      PkcsMechanism.mechanism = CKM_CAST_MAC;
      break;

    case CSSM_ALGID_CAST3:
      PkcsMechanism.mechanism = CKM_CAST3_MAC;
      break;

    case CSSM_ALGID_CAST5:
      PkcsMechanism.mechanism = CKM_CAST5_MAC;
      break;

    case CSSM_ALGID_IDEA:
      PkcsMechanism.mechanism = CKM_IDEA_MAC;
      break;

    case CSSM_ALGID_CDMF:
      PkcsMechanism.mechanism = CKM_CDMF_MAC;
      break;
    
    case CSSM_ALGID_MD2:
      PkcsMechanism.mechanism = CKM_MD2_HMAC;
      break;

    case CSSM_ALGID_MD5:
      PkcsMechanism.mechanism = CKM_MD5_HMAC;
      break;

    case CSSM_ALGID_SHA1:
      PkcsMechanism.mechanism = CKM_SHA_1_HMAC;
      break;

    case CSSM_ALGID_SSL3MD5_MAC:
      pCssmOutputSizeAttr = CSSM_GetContextAttribute(pCssmContext, CSSM_ATTRIBUTE_OUTPUT_SIZE);
      if (pCssmOutputSizeAttr == NULL)
        return SetErr(CSSM_CSP_PARAM_NO_OUTPUT_SIZE);
      PkcsMechanism.mechanism = CKM_SSL3_MD5_MAC;
      PkcsMacGeneralParams = pCssmOutputSizeAttr->Attribute.Uint32;
      PkcsMechanism.pParameter = &PkcsMacGeneralParams;
      PkcsMechanism.ulParameterLen = sizeof(PkcsMacGeneralParams);
      break;

    case CSSM_ALGID_SSL3SHA1_MAC:
      pCssmOutputSizeAttr = CSSM_GetContextAttribute(pCssmContext, CSSM_ATTRIBUTE_OUTPUT_SIZE);
      if (pCssmOutputSizeAttr == NULL)
        return SetErr(CSSM_CSP_PARAM_NO_OUTPUT_SIZE);
      PkcsMechanism.mechanism = CKM_SSL3_SHA1_MAC;
      PkcsMacGeneralParams = pCssmOutputSizeAttr->Attribute.Uint32;
      PkcsMechanism.pParameter = &PkcsMacGeneralParams;
      PkcsMechanism.ulParameterLen = sizeof(PkcsMacGeneralParams);
      break;

#endif
      
    case CSSM_ALGID_RC2:
      PkcsMechanism.mechanism = CKM_RC2_MAC;
      pCssmEffectiveKeyBitsAttr = CSSM_GetContextAttribute(pCssmContext, 
                                 CSSM_ATTRIBUTE_EFFECTIVE_BITS);
      if (pCssmEffectiveKeyBitsAttr == NULL)
        return SetErr(CSSM_CSP_PARAM_NO_EFFECTIVE_BITS);

#ifdef PKCS11_V20
      PkcsRc2Params = pCssmEffectiveKeyBitsAttr->Attribute.Uint32;
      PkcsMechanism.pParameter = &PkcsRc2Params;
      PkcsMechanism.ulParameterLen = sizeof(PkcsRc2Params);
#else
      PkcsRc2Params = (CK_USHORT) pCssmEffectiveKeyBitsAttr->Attribute.Uint32;
      PkcsRc2Params = htons(PkcsRc2Params);
      PkcsMechanism.pParameter = &PkcsRc2Params;
      PkcsMechanism.usParameterLen = sizeof(PkcsRc2Params);
#endif
      break;

    case CSSM_ALGID_DES:
      PkcsMechanism.mechanism = CKM_DES_MAC;
      break;

    case CSSM_ALGID_3DES_3KEY:
    case CSSM_ALGID_3DES_2KEY:
      PkcsMechanism.mechanism = CKM_DES3_MAC;
      break;

    default:
      return SetErr(CSSM_CSP_ALGORITHM_UNSUPPORTED);
  }

  // Get key

  pCssmKeyAttr = CSSM_GetContextAttribute(pCssmContext, CSSM_ATTRIBUTE_KEY);
  if (pCssmKeyAttr == NULL)
    return SetErr(CSSM_CSP_INVALID_KEY_POINTER);

  pCssmKey = pCssmKeyAttr->Attribute.Key;

  if (pCssmKey->KeyHeader.BlobType == CSSM_KEYBLOB_REFERENCE &&
    pCssmKey->KeyHeader.Format == CSSM_KEYBLOB_REF_FORMAT_INTEGER &&
    pCssmKey->KeyHeader.KeyClass == CSSM_KEYCLASS_SESSION_KEY &&
    pCssmKey->KeyHeader.AlgorithmId == pCssmContext->AlgorithmType)
  {
    if (pCssmKey->KeyData.Data == NULL)
      return SetErr(CSSM_CSP_INVALID_KEY_POINTER);

    hPkcsKey = *((CK_OBJECT_HANDLE*) pCssmKey->KeyData.Data);
  }
  else
    return SetErr(CSSM_CSP_INVALID_KEY);


  if ((PkcsStatus = C_SignInit(pMsmSession->PkcsSessionHandle, 
                 &PkcsMechanism,
                 hPkcsKey)) != CKR_OK)
    return SetErr(PkcsStatus);

  return CSSM_OK;

}



/*****************************************************************************
 * Function: GenerateMacUpdate 
 * 
 * Update stage of mac operation.
 *
 * Input:
 *  CssmCSPHandle   - Attach session handle 
 *  CssmCCHandle    - Context handle
 *  pCssmDataBufs   - Data to be digested
 *  CssmDataBufCount  - Number of input buffers
 *   
 * Output:
 *  None
 *   
 * Returns:
 *  CSSM_OK       - Successful      
 *  CSSM_FAIL     - Failed
 *
 */

CSSM_RETURN CSSMAPI GenerateMacUpdate(
  CSSM_CSP_HANDLE CssmCSPHandle,
  CSSM_CC_HANDLE CssmCCHandle,
  const CSSM_DATA_PTR pCssmDataBufs,
  uint32 CssmDataBufCount)
{

  CSSM_CONTEXT_PTR      pCssmContext;

  CK_RV           PkcsStatus;

  MSMSESSION_PTR        pMsmSession;
  uint32            CssmContextType;



  if ((pMsmSession = FindMsmSession(CssmCSPHandle)) == NULL)
    return SetErr(CSSM_CSP_INVALID_CSP_HANDLE);
  
  if ((pCssmContext = CSSM_GetContext(CssmCCHandle)) == NULL)
    return SetErr(CSSM_INVALID_CONTEXT_HANDLE);

  CssmContextType = pCssmContext->ContextType;
  CSSM_FreeContext(pCssmContext);

  if (CssmContextType != CSSM_ALGCLASS_MAC) 
    return SetErr(CSSM_CSP_INVALID_CONTEXT);

  if (CssmDataBufCount != 1)
    return SetErr(CSSM_CSP_VECTOROFBUFS_UNSUPPORTED);

  if (pCssmDataBufs == NULL)
    return SetErr(CSSM_CSP_INVALID_POINTER);

  if (pCssmDataBufs->Data == NULL)
    return SetErr(CSSM_CSP_INVALID_DATA_POINTER);

#ifdef PKCS11_V20
  if ((PkcsStatus = C_SignUpdate(pMsmSession->PkcsSessionHandle,
                   pCssmDataBufs->Data, 
                   pCssmDataBufs->Length)) != CKR_OK)
#else
  if ((PkcsStatus = C_SignUpdate(pMsmSession->PkcsSessionHandle,
                   pCssmDataBufs->Data, 
                   (CK_USHORT) pCssmDataBufs->Length)) != CKR_OK)
#endif
    return SetErr(PkcsStatus);

  return CSSM_OK;

}



/*****************************************************************************
 * Function: GenerateMacFinal 
 * 
 * Final stage mac operation.
 *
 * Input:
 *  CssmCSPHandle   - Attach session handle 
 *  CssmCCHandle    - Context handle
 *   
 * Output:
 *  pCssmMac      - Computed mac
 *   
 * Returns:
 *  CSSM_OK       - Successful      
 *  CSSM_FAIL     - Failed
 *
 */

CSSM_RETURN CSSMAPI GenerateMacFinal(
  CSSM_CSP_HANDLE CssmCSPHandle,
  CSSM_CC_HANDLE CssmCCHandle,
  CSSM_DATA_PTR pCssmMac)
{

  CSSM_CONTEXT_PTR      pCssmContext;
  CSSM_CONTEXT_ATTRIBUTE_PTR  pCssmWordSizeAttr = NULL;
  CSSM_CONTEXT_ATTRIBUTE_PTR  pCssmOutputSizeAttr = NULL;

  CK_RV           PkcsStatus;
      
  MSMSESSION_PTR        pMsmSession;
  CSSM_BOOL         MsmBufferAllocated = CSSM_FALSE;
  uint32            CssmContextType;

#ifdef PKCS11_V20
  CK_ULONG          length;
#else
  CK_USHORT         length;
#endif




  if ((pMsmSession = FindMsmSession(CssmCSPHandle)) == NULL)
    return SetErr(CSSM_CSP_INVALID_CSP_HANDLE);
  
  if ((pCssmContext = CSSM_GetContext(CssmCCHandle)) == NULL)
    return SetErr(CSSM_INVALID_CONTEXT_HANDLE);

  CssmContextType = pCssmContext->ContextType;

  if (CssmContextType != CSSM_ALGCLASS_MAC) 
    return SetErr(CSSM_CSP_INVALID_CONTEXT);

  // Buffer checking and allocation 

  if (pCssmMac == NULL)
  {
    CSSM_FreeContext(pCssmContext);
    return SetErr(CSSM_CSP_INVALID_POINTER);
  }

  if (((pCssmMac->Length == 0) && (pCssmMac->Data != NULL)) ||
    ((pCssmMac->Length != 0) && (pCssmMac->Data == NULL)))
  {
    CSSM_FreeContext(pCssmContext);
    return SetErr(CSSM_CSP_INVALID_DATA_POINTER);   
  }

  if (pCssmMac->Data == NULL)
  {
    switch (pCssmContext->AlgorithmType)
    {
#ifdef PKCS11_V20
      case CSSM_ALGID_RC5:
      case CSSM_ALGID_CAST:
      case CSSM_ALGID_CAST3:
      case CSSM_ALGID_CAST5:
      case CSSM_ALGID_IDEA:
      case CSSM_ALGID_CDMF:
        pCssmWordSizeAttr = CSSM_GetContextAttribute(pCssmContext, CSSM_ATTRIBUTE_BLOCK_SIZE);
        if (pCssmWordSizeAttr == NULL)
          return SetErr(CSSM_CSP_PARAM_NO_PARAM);   
          //return SetErr(CSSM_CSP_PARAM_NO_BLOCK_SIZE);    

        pCssmMac->Length = pCssmWordSizeAttr->Attribute.Uint32 / 2; 
        break;
        
      case CSSM_ALGID_MD2:
      case CSSM_ALGID_MD5:
        pCssmMac->Length = MDXDIGESTLEN;
        break;

      case CSSM_ALGID_SHA1:
        pCssmMac->Length = SHA1DIGESTLEN;
        break;

      case CSSM_ALGID_SSL3MD5_MAC:
      case CSSM_ALGID_SSL3SHA1_MAC:
        pCssmOutputSizeAttr = CSSM_GetContextAttribute(pCssmContext, CSSM_ATTRIBUTE_OUTPUT_SIZE);
        if (pCssmOutputSizeAttr == NULL)
          return SetErr(CSSM_CSP_PARAM_NO_OUTPUT_SIZE);
        pCssmMac->Length = pCssmOutputSizeAttr->Attribute.Uint32;
        break;
#endif

      case CSSM_ALGID_RC2:
      case CSSM_ALGID_DES:
      case CSSM_ALGID_3DES_3KEY:
      case CSSM_ALGID_3DES_2KEY:
        pCssmMac->Length = SYMMETRICMACLEN;
      break;
    }

    if ((pCssmMac->Data = CssmMemFuncs.calloc_func(CssmCSPHandle, 
                             1,
                             pCssmMac->Length)) == NULL)
    {
      CSSM_FreeContext(pCssmContext); 
      return SetErr(CSSM_CALLOC_FAILED);
    }

    MsmBufferAllocated = CSSM_TRUE;
  }
  else
  {
    switch (pCssmContext->AlgorithmType)
    {
#ifdef PKCS11_V20
      case CSSM_ALGID_RC5:
      case CSSM_ALGID_CAST:
      case CSSM_ALGID_CAST3:
      case CSSM_ALGID_CAST5:
      case CSSM_ALGID_IDEA:
      case CSSM_ALGID_CDMF:
        pCssmWordSizeAttr = CSSM_GetContextAttribute(pCssmContext, CSSM_ATTRIBUTE_BLOCK_SIZE);
        if (pCssmWordSizeAttr == NULL)
          return SetErr(CSSM_CSP_PARAM_NO_PARAM);   
          //return SetErr(CSSM_CSP_PARAM_NO_BLOCK_SIZE);    

        if (pCssmMac->Length < pCssmWordSizeAttr->Attribute.Uint32 / 2)
          return(CSSM_CSP_INVALID_PARAM_LENGTH);
        
        break;
        
      case CSSM_ALGID_MD2:
      case CSSM_ALGID_MD5:
        if (pCssmMac->Length < MDXDIGESTLEN)
          return(CSSM_CSP_INVALID_PARAM_LENGTH);
        break;

      case CSSM_ALGID_SHA1:
        if (pCssmMac->Length < SHA1DIGESTLEN)
          return(CSSM_CSP_INVALID_PARAM_LENGTH);
        break;

      case CSSM_ALGID_SSL3MD5_MAC:
      case CSSM_ALGID_SSL3SHA1_MAC:
        pCssmOutputSizeAttr = CSSM_GetContextAttribute(pCssmContext, CSSM_ATTRIBUTE_OUTPUT_SIZE);
        if (pCssmOutputSizeAttr == NULL)
          return SetErr(CSSM_CSP_PARAM_NO_OUTPUT_SIZE);
        if (pCssmMac->Length < pCssmOutputSizeAttr->Attribute.Uint32)
          return(CSSM_CSP_INVALID_PARAM_LENGTH);
        break;
#endif

      case CSSM_ALGID_RC2:
      case CSSM_ALGID_DES:
      case CSSM_ALGID_3DES_3KEY:
      case CSSM_ALGID_3DES_2KEY:
        if (pCssmMac->Length < SYMMETRICMACLEN)
          return(CSSM_CSP_INVALID_PARAM_LENGTH);
      break;
    }

  }


  // Now do the final
#ifdef PKCS11_V20
  length = pCssmMac->Length;
  if ((PkcsStatus = C_SignFinal(pMsmSession->PkcsSessionHandle, 
                  pCssmMac->Data,
                  &length)) != CKR_OK)
#else
  length = (CK_USHORT) pCssmMac->Length;
  if ((PkcsStatus = C_SignFinal(pMsmSession->PkcsSessionHandle, 
                  pCssmMac->Data,
                  &length)) != CKR_OK)
#endif
  {
    if (MsmBufferAllocated)   
    {
      CssmMemFuncs.free_func(CssmCSPHandle,  pCssmMac->Data);
      pCssmMac->Length = 0;
      pCssmMac->Data = NULL_PTR;
    }
    
    CSSM_FreeContext(pCssmContext); 
    return SetErr(PkcsStatus);
  }

  pCssmMac->Length = length;
  CSSM_FreeContext(pCssmContext); 
  return CSSM_OK;

}



/*****************************************************************************
 * Function: VerifyMac 
 * 
 * Verify message authentication code.
 *
 * Input:
 *  CssmCSPHandle   - Attach session handle 
 *  CssmCCHandle    - Context handle
 *  pCssmContext    - Pointer to context 
 *  pCssmDataBufs   - Data to be mac'ed
 *  CssmDataBufCount  - Number of input buffers
 *   
 * Output:
 *  pCssmMac      - Computed mac
 *   
 * Returns:
 *  CSSM_OK       - Successful      
 *  CSSM_FAIL     - Failed
 *
 */

CSSM_RETURN CSSMAPI VerifyMac(
  CSSM_CSP_HANDLE CssmCSPHandle,
  CSSM_CC_HANDLE CssmCCHandle,
  const CSSM_CONTEXT_PTR pCssmContext,
  const CSSM_DATA_PTR pCssmDataBufs,
  uint32 CssmDataBufCount,
  CSSM_DATA_PTR pCssmMac)
{
  int CssmRc = CSSM_OK;

  if ((CssmRc = VerifyMacInit(CssmCSPHandle, CssmCCHandle, pCssmContext)) != CSSM_OK)
    return CssmRc;
  
  if ((CssmRc = VerifyMacUpdate(CssmCSPHandle, CssmCCHandle, pCssmDataBufs, CssmDataBufCount)) != CSSM_OK)
    return CssmRc;

  CssmRc = VerifyMacFinal(CssmCSPHandle, CssmCCHandle, pCssmMac);
  return CssmRc;
}
  


/*****************************************************************************
 * Function: VerifyMacInit 
 * 
 * Init stage of mac operation.
 *
 * Input:
 *  CssmCSPHandle   - Attach session handle 
 *  CssmCCHandle    - Context handle
 *  pCssmContext    - Pointer to context 
 *   
 * Output:
 *  None
 *   
 * Returns:
 *  CSSM_OK       - Successful      
 *  CSSM_FAIL     - Failed
 *
 */

CSSM_RETURN CSSMAPI VerifyMacInit(
  CSSM_CSP_HANDLE CssmCSPHandle,
  CSSM_CC_HANDLE CssmCCHandle,
  const CSSM_CONTEXT_PTR pCssmContext)
{

  CSSM_CONTEXT_ATTRIBUTE_PTR  pCssmKeyAttr;
  CSSM_CONTEXT_ATTRIBUTE_PTR  pCssmEffectiveKeyBitsAttr = NULL;
  CSSM_CONTEXT_ATTRIBUTE_PTR  pCssmWordSizeAttr = NULL;
  CSSM_CONTEXT_ATTRIBUTE_PTR  pCssmRoundsAttr = NULL;
  CSSM_CONTEXT_ATTRIBUTE_PTR  pCssmOutputSizeAttr = NULL;


  CSSM_KEY_PTR        pCssmKey;


  CK_RV           PkcsStatus;
  CK_MECHANISM        PkcsMechanism = {0, NULL_PTR, 0};
  CK_OBJECT_HANDLE      hPkcsKey;
#ifdef PKCS11_V20
  CK_RC2_PARAMS       PkcsRc2Params;
#else
  CK_BYTE           PkcsRc2Params[2];
  CK_USHORT         MsmTemp;
#endif

#ifdef PKCS11_V20
  CK_RC5_PARAMS       PkcsRc5Params;
  CK_MAC_GENERAL_PARAMS   PkcsMacGeneralParams;
#endif


  MSMSESSION_PTR        pMsmSession;
  CSSM_BOOL         MsmBufferAllocated = CSSM_FALSE;
  


  if ((pMsmSession = FindMsmSession(CssmCSPHandle)) == NULL)
    return SetErr(CSSM_CSP_INVALID_CSP_HANDLE);


  // Setting things up for init

  switch (pCssmContext->AlgorithmType)
  {
#ifdef PKCS11_V20
    case CSSM_ALGID_RC5:
      pCssmWordSizeAttr = CSSM_GetContextAttribute(pCssmContext, CSSM_ATTRIBUTE_BLOCK_SIZE);
      if (pCssmWordSizeAttr == NULL)
        return SetErr(CSSM_CSP_PARAM_NO_PARAM);   
        //return SetErr(CSSM_CSP_PARAM_NO_BLOCK_SIZE);    

      pCssmRoundsAttr = CSSM_GetContextAttribute(pCssmContext, CSSM_ATTRIBUTE_ROUNDS);
      if (pCssmRoundsAttr == NULL)
        return SetErr(CSSM_CSP_PARAM_NO_ROUNDS);

      PkcsMechanism.mechanism = CKM_RC5_MAC;
      PkcsRc5Params.ulWordsize = pCssmWordSizeAttr->Attribute.Uint32; 
      PkcsRc5Params.ulRounds = pCssmRoundsAttr->Attribute.Uint32;   
      PkcsMechanism.pParameter = &PkcsRc5Params;
      PkcsMechanism.ulParameterLen = sizeof(PkcsRc5Params);

      break;

    case CSSM_ALGID_CAST:
      PkcsMechanism.mechanism = CKM_CAST_MAC;
      break;

    case CSSM_ALGID_CAST3:
      PkcsMechanism.mechanism = CKM_CAST3_MAC;
      break;

    case CSSM_ALGID_CAST5:
      PkcsMechanism.mechanism = CKM_CAST5_MAC;
      break;

    case CSSM_ALGID_IDEA:
      PkcsMechanism.mechanism = CKM_IDEA_MAC;
      break;

    case CSSM_ALGID_CDMF:
      PkcsMechanism.mechanism = CKM_CDMF_MAC;
      break;
    
    case CSSM_ALGID_MD2:
      PkcsMechanism.mechanism = CKM_MD2_HMAC;
      break;

    case CSSM_ALGID_MD5:
      PkcsMechanism.mechanism = CKM_MD5_HMAC;
      break;

    case CSSM_ALGID_SHA1:
      PkcsMechanism.mechanism = CKM_SHA_1_HMAC;
      break;

    case CSSM_ALGID_SSL3MD5_MAC:
      pCssmOutputSizeAttr = CSSM_GetContextAttribute(pCssmContext, CSSM_ATTRIBUTE_OUTPUT_SIZE);
      if (pCssmOutputSizeAttr == NULL)
        return SetErr(CSSM_CSP_PARAM_NO_OUTPUT_SIZE);
      PkcsMechanism.mechanism = CKM_SSL3_MD5_MAC;
      PkcsMacGeneralParams = pCssmOutputSizeAttr->Attribute.Uint32;
      PkcsMechanism.pParameter = &PkcsMacGeneralParams;
      PkcsMechanism.ulParameterLen = sizeof(PkcsMacGeneralParams);
      break;

    case CSSM_ALGID_SSL3SHA1_MAC:
      pCssmOutputSizeAttr = CSSM_GetContextAttribute(pCssmContext, CSSM_ATTRIBUTE_OUTPUT_SIZE);
      if (pCssmOutputSizeAttr == NULL)
        return SetErr(CSSM_CSP_PARAM_NO_OUTPUT_SIZE);
      PkcsMechanism.mechanism = CKM_SSL3_SHA1_MAC;
      PkcsMacGeneralParams = pCssmOutputSizeAttr->Attribute.Uint32;
      PkcsMechanism.pParameter = &PkcsMacGeneralParams;
      PkcsMechanism.ulParameterLen = sizeof(PkcsMacGeneralParams);
      break;

#endif
      
    case CSSM_ALGID_RC2:
      PkcsMechanism.mechanism = CKM_RC2_MAC;
      pCssmEffectiveKeyBitsAttr = CSSM_GetContextAttribute(pCssmContext, 
                                 CSSM_ATTRIBUTE_EFFECTIVE_BITS);
      if (pCssmEffectiveKeyBitsAttr == NULL)
        return SetErr(CSSM_CSP_PARAM_NO_EFFECTIVE_BITS);

#ifdef PKCS11_V20
      PkcsRc2Params = pCssmEffectiveKeyBitsAttr->Attribute.Uint32;
      PkcsMechanism.pParameter = &PkcsRc2Params;
      PkcsMechanism.ulParameterLen = sizeof(PkcsRc2Params);
#else
      MsmTemp = (CK_USHORT) pCssmEffectiveKeyBitsAttr->Attribute.Uint32;
      PkcsRc2Params[0] = (CK_BYTE) (MsmTemp >> 8);
      MsmTemp = (CK_USHORT) pCssmEffectiveKeyBitsAttr->Attribute.Uint32;
      PkcsRc2Params[1] = (CK_BYTE) (MsmTemp & 0x00FF);
      PkcsMechanism.pParameter = &PkcsRc2Params;
      PkcsMechanism.usParameterLen = sizeof(PkcsRc2Params);
#endif
      break;

    case CSSM_ALGID_DES:
      PkcsMechanism.mechanism = CKM_DES_MAC;
      break;

    case CSSM_ALGID_3DES_3KEY:
    case CSSM_ALGID_3DES_2KEY:
      PkcsMechanism.mechanism = CKM_DES3_MAC;
      break;

    default:
      return SetErr(CSSM_CSP_INVALID_ALGORITHM);
  }

  // Get key

  pCssmKeyAttr = CSSM_GetContextAttribute(pCssmContext, CSSM_ATTRIBUTE_KEY);
  if (pCssmKeyAttr == NULL)
    return SetErr(CSSM_CSP_INVALID_KEY_POINTER);

  pCssmKey = pCssmKeyAttr->Attribute.Key;

  if (pCssmKey->KeyHeader.BlobType == CSSM_KEYBLOB_REFERENCE &&
    pCssmKey->KeyHeader.Format == CSSM_KEYBLOB_REF_FORMAT_INTEGER &&
    pCssmKey->KeyHeader.KeyClass == CSSM_KEYCLASS_SESSION_KEY &&
    (pCssmKey->KeyHeader.AlgorithmId == pCssmContext->AlgorithmType))
  {
    if (pCssmKey->KeyData.Data == NULL)
      return SetErr(CSSM_CSP_INVALID_KEY_POINTER);

    hPkcsKey = *((CK_OBJECT_HANDLE*) pCssmKey->KeyData.Data);
  }
  else
    return SetErr(CSSM_CSP_INVALID_KEY);


  if ((PkcsStatus = C_VerifyInit(pMsmSession->PkcsSessionHandle, 
                 &PkcsMechanism,
                 hPkcsKey)) != CKR_OK)
    return SetErr(PkcsStatus);

  return CSSM_OK;

}



/*****************************************************************************
 * Function: VerifyMacUpdate
 *
 * Update stage of mac operation.
 *
 * Input:
 *  CssmCSPHandle   - Attach session handle 
 *  CssmCCHandle    - Context handle
 *  pCssmDataBufs   - Data to be digested
 *  CssmDataBufCount  - Number of input buffers
 *   
 * Output:
 *  None
 *   
 * Returns:
 *  CSSM_OK       - Successful      
 *  CSSM_FAIL     - Failed
 *
 */

CSSM_RETURN CSSMAPI VerifyMacUpdate(
  CSSM_CSP_HANDLE CssmCSPHandle,
  CSSM_CC_HANDLE CssmCCHandle,
  const CSSM_DATA_PTR pCssmDataBufs,
  uint32 CssmDataBufCount)
{

  CSSM_CONTEXT_PTR      pCssmContext;

  CK_RV           PkcsStatus;

  MSMSESSION_PTR        pMsmSession;
  CSSM_BOOL         MsmBufferAllocated = CSSM_FALSE;
  uint32            CssmContextType;



  if ((pMsmSession = FindMsmSession(CssmCSPHandle)) == NULL)
    return SetErr(CSSM_CSP_INVALID_CSP_HANDLE);
  
  if ((pCssmContext = CSSM_GetContext(CssmCCHandle)) == NULL)
    return SetErr(CSSM_INVALID_CONTEXT_HANDLE);

  CssmContextType = pCssmContext->ContextType;
  CSSM_FreeContext(pCssmContext);

  if (CssmContextType != CSSM_ALGCLASS_MAC) 
    return SetErr(CSSM_CSP_INVALID_CONTEXT);  


  if (CssmDataBufCount != 1)
    return SetErr(CSSM_CSP_VECTOROFBUFS_UNSUPPORTED);

  if (pCssmDataBufs == NULL)
    return SetErr(CSSM_CSP_INVALID_POINTER);

  if (pCssmDataBufs->Data == NULL)
    return SetErr(CSSM_CSP_INVALID_DATA_POINTER);

#ifdef PKCS11_V20
  if ((PkcsStatus = C_VerifyUpdate(pMsmSession->PkcsSessionHandle,
                     pCssmDataBufs->Data, 
                     pCssmDataBufs->Length)) != CKR_OK)
#else
  if ((PkcsStatus = C_VerifyUpdate(pMsmSession->PkcsSessionHandle,
                     pCssmDataBufs->Data, 
                     (CK_USHORT)pCssmDataBufs->Length)) != CKR_OK)
#endif
    return SetErr(PkcsStatus);

  return CSSM_OK;

}



/*****************************************************************************
 * Function: VerifyMacFinal - Final stage mac operation.
 *
 * Input:
 *  CssmCSPHandle   - Attach session handle 
 *  CssmCCHandle    - Context handle
 *   
 * Output:
 *  pCssmMac      - Computed mac
 *   
 * Returns:
 *  CSSM_OK       - Successful      
 *  CSSM_FAIL     - Failed
 *
 */

CSSM_RETURN CSSMAPI VerifyMacFinal(
  CSSM_CSP_HANDLE CssmCSPHandle,
  CSSM_CC_HANDLE CssmCCHandle,
  CSSM_DATA_PTR pCssmMac)
{

  CSSM_CONTEXT_PTR      pCssmContext;

  CK_RV           PkcsStatus;
      
  MSMSESSION_PTR        pMsmSession;
  CSSM_BOOL         MsmBufferAllocated = CSSM_FALSE;
  uint32            CssmContextType;



  if ((pMsmSession = FindMsmSession(CssmCSPHandle)) == NULL)
    return SetErr(CSSM_CSP_INVALID_CSP_HANDLE);
  
  if ((pCssmContext = CSSM_GetContext(CssmCCHandle)) == NULL)
    return SetErr(CSSM_INVALID_CONTEXT_HANDLE);

  CssmContextType = pCssmContext->ContextType;
  CSSM_FreeContext(pCssmContext);

  if (CssmContextType != CSSM_ALGCLASS_MAC) 
    return SetErr(CSSM_CSP_INVALID_CONTEXT);


  // Buffer checking  

  if (pCssmMac == NULL)
    return SetErr(CSSM_CSP_INVALID_POINTER);

  if (pCssmMac->Data == NULL || pCssmMac->Length == 0)
    return SetErr(CSSM_CSP_INVALID_DATA_POINTER);   

  // Now do the final

#ifdef PKCS11_V20
  if ((PkcsStatus = C_VerifyFinal(pMsmSession->PkcsSessionHandle, 
                      pCssmMac->Data,
                    pCssmMac->Length)) != CKR_OK)
#else
  if ((PkcsStatus = C_VerifyFinal(pMsmSession->PkcsSessionHandle, 
                      pCssmMac->Data,
                    (CK_USHORT) pCssmMac->Length)) != CKR_OK)
#endif
    return SetErr(PkcsStatus);

  return CSSM_OK;
}
