/* ***************************************************************** *
 * 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: DigestData - 
 *
 * Compute digest of input data.
 *
 * Input:
 *  CssmCSPHandle   - Attach session handle 
 *  CssmCCHandle    - Context handle
 *  pCssmContext    - Pointer to context 
 *  pCssmDataBufs   - Data to be digested
 *  CssmDataBufCount  - Number of input buffers
 *   
 * Output:
 *  pCssmDigest     - Computed digest
 *   
 * Returns:
 *  CSSM_OK       - Successful      
 *  CSSM_FAIL     - Failed
 *
 */

CSSM_RETURN CSSMAPI DigestData(
  CSSM_CSP_HANDLE CssmCSPHandle,
  CSSM_CC_HANDLE CssmCCHandle,
  const CSSM_CONTEXT_PTR pCssmContext,
  const CSSM_DATA_PTR pCssmDataBufs,
  uint32 CssmDataBufCount,
  CSSM_DATA_PTR pCssmDigest)
{

  int CssmRc = CSSM_OK;
  
  if ((CssmRc = DigestDataInit(CssmCSPHandle, CssmCCHandle, pCssmContext)) != CSSM_OK)
    return CssmRc;

  if ((CssmRc = DigestDataUpdate(CssmCSPHandle, CssmCCHandle, pCssmDataBufs, CssmDataBufCount)) != CSSM_OK)
    return CssmRc;

  CssmRc = DigestDataFinal(CssmCSPHandle, CssmCCHandle, pCssmDigest);
  return CssmRc;

}



/*****************************************************************************
 * Function: DigestDataInit - 
 *
 * Init stage of digest 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 DigestDataInit(
  CSSM_CSP_HANDLE CssmCSPHandle,
  CSSM_CC_HANDLE CssmCCHandle,
  const CSSM_CONTEXT_PTR pCssmContext)
{

  CK_RV           PkcsStatus;
  CK_MECHANISM        PkcsMechanism = {0, NULL_PTR, 0};

  MSMSESSION_PTR        pMsmSession;
  CSSM_BOOL         MsmBufferAllocated = CSSM_FALSE;



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

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

  if (pCssmContext->AlgorithmType == CSSM_ALGID_MD2)
    PkcsMechanism.mechanism = CKM_MD2;
  else if (pCssmContext->AlgorithmType == CSSM_ALGID_MD5)
    PkcsMechanism.mechanism = CKM_MD5;
  else if (pCssmContext->AlgorithmType == CSSM_ALGID_SHA1)
    PkcsMechanism.mechanism = CKM_SHA_1;
  else
    return SetErr(CSSM_CSP_ALGORITHM_UNSUPPORTED);

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

  return CSSM_OK;

}



/*****************************************************************************
 * Function: DigestDataUpdate - 
 *
 * Update stage of digest 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 DigestDataUpdate(
  CSSM_CSP_HANDLE CssmCSPHandle,
  CSSM_CC_HANDLE CssmCCHandle,
  const CSSM_DATA_PTR pCssmDataBufs,
  uint32 CssmDataBufCount)
{

  CSSM_CONTEXT_PTR      pCssmContext;
  uint32            CssmContextType;

  CK_RV           PkcsStatus;

  MSMSESSION_PTR        pMsmSession;



  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_DIGEST)
    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_DigestUpdate(pMsmSession->PkcsSessionHandle, 
                   pCssmDataBufs->Data, 
                   pCssmDataBufs->Length)) != CKR_OK)
#else
  if ((PkcsStatus = C_DigestUpdate(pMsmSession->PkcsSessionHandle, 
                   pCssmDataBufs->Data, 
                   (CK_USHORT)pCssmDataBufs->Length)) != CKR_OK)
#endif
    return SetErr(PkcsStatus);

  return CSSM_OK;

}



/*****************************************************************************
 * Function: DigestDataFinal - 
 *
 * Final stage of digest operation.
 *
 * Input:
 *  CssmCSPHandle   - Attach session handle 
 *  CssmCCHandle    - Context handle
 *   
 * Output:
 *  pCssmDigest     - Computed digest
 *   
 * Returns:
 *  CSSM_OK       - Successful      
 *  CSSM_FAIL     - Failed
 *
 */

CSSM_RETURN CSSMAPI DigestDataFinal(
  CSSM_CSP_HANDLE CssmCSPHandle,
  CSSM_CC_HANDLE CssmCCHandle,
  CSSM_DATA_PTR pCssmDigest)
{

  CSSM_CONTEXT_PTR      pCssmContext;
  uint32            CssmContextType;
  uint32            CssmAlgoType;

  CK_RV           PkcsStatus;

  MSMSESSION_PTR        pMsmSession;
  CSSM_BOOL         MsmBufferAllocated = CSSM_FALSE;

#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;
  CssmAlgoType = pCssmContext->AlgorithmType;
  CSSM_FreeContext(pCssmContext);

  if (CssmContextType != CSSM_ALGCLASS_DIGEST)
    return SetErr(CSSM_CSP_INVALID_CONTEXT_HANDLE);

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

  if (((pCssmDigest->Length == 0) && (pCssmDigest->Data != NULL)) ||
    ((pCssmDigest->Length != 0) && (pCssmDigest->Data == NULL)))
    return SetErr(CSSM_CSP_INVALID_DATA_POINTER);

  if (pCssmDigest->Data == NULL)
  {
    if (CssmAlgoType == CSSM_ALGID_SHA1)
      pCssmDigest->Length = SHA1DIGESTLEN;
    else
      pCssmDigest->Length = MDXDIGESTLEN;

    if ((pCssmDigest->Data = CssmMemFuncs.calloc_func(CssmCSPHandle, 
                              1, 
                              pCssmDigest->Length)) == NULL)
      return SetErr(CSSM_CALLOC_FAILED);
    
    MsmBufferAllocated = CSSM_TRUE;

  }


#ifdef PKCS11_V20
  if ((PkcsStatus = C_DigestFinal(pMsmSession->PkcsSessionHandle, 
                  pCssmDigest->Data, 
                  &length)) != CKR_OK)
#else
  if ((PkcsStatus = C_DigestFinal(pMsmSession->PkcsSessionHandle, 
                  pCssmDigest->Data, 
                  &length)) != CKR_OK)
#endif
  {
    if (MsmBufferAllocated)
    {
      CssmMemFuncs.free_func(CssmCSPHandle,  pCssmDigest->Data);
      pCssmDigest->Length = 0;
      pCssmDigest->Data = NULL;
    }

    return SetErr(PkcsStatus);
  }

  pCssmDigest->Length = length;
  return CSSM_OK;

}
