/* ***************************************************************** *
 * 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: SignData 
 *
 * Sign input data.
 *
 * Input:
 *  CssmCSPHandle   - Attach session handle 
 *  CssmCCHandle    - Context handle
 *  pCssmContext    - Pointer to context 
 *  pCssmDataBufs   - Data to be signed
 *  CssmDataBufCount  - Number of input buffers
 *   
 * Output:
 *  pCssmSignature    - Computed signature
 *   
 * Returns:
 *  CSSM_OK       - Successful      
 *  CSSM_FAIL     - Failed
 *
 */

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

  int CssmRc = CSSM_OK;



  switch (pCssmContext->AlgorithmType)
  {
    case CSSM_ALGID_RSA_PKCS:
    case CSSM_ALGID_RSA_ISO9796:
    case CSSM_ALGID_RSA_RAW:
    case CSSM_ALGID_DSA:
    case CSSM_ALGID_ECDSA:
    case CSSM_ALGID_FortezzaTimestamp:  
      return SignDataSinglePart(CssmCSPHandle,
                    CssmCCHandle,
                    pCssmContext,
                    pCssmDataBufs,
                    CssmDataBufCount,
                    pCssmSignature);


#ifdef PKCS11_V20
    case CSSM_ALGID_MD2WithRSA:
    case CSSM_ALGID_MD5WithRSA:
    case CSSM_ALGID_SHA1WithRSA:
    case CSSM_ALGID_SHA1WithDSA:
      if ((CssmRc = SignDataInit(CssmCSPHandle, CssmCCHandle, pCssmContext)) != CSSM_OK)
        return CssmRc;
  
      if ((CssmRc = SignDataUpdate(CssmCSPHandle, CssmCCHandle, pCssmDataBufs, CssmDataBufCount)) != CSSM_OK)
        return CssmRc;

      CssmRc = SignDataFinal(CssmCSPHandle, CssmCCHandle, pCssmSignature);
      return CssmRc;
#endif

    default:
      return SetErr(CSSM_CSP_ALGORITHM_UNSUPPORTED);

  }

}



/*****************************************************************************
 * Function: SignDataSinglePart 
 * 
 * Sign input data in one stage.
 *
 * Input:
 *  CssmCSPHandle   - Attach session handle 
 *  CssmCCHandle    - Context handle
 *  pCssmContext    - Pointer to context 
 *  pCssmDataBufs   - Data to be signed
 *  CssmDataBufCount  - Number of input buffers
 *   
 * Output:
 *  pCssmSignature    - Computed signature
 *   
 * Returns:
 *  CSSM_OK       - Successful      
 *  CSSM_FAIL     - Failed
 *
 */

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

  CSSM_CONTEXT_ATTRIBUTE_PTR  pCssmKeyAttr;
  CSSM_KEY_PTR        pCssmKey;

  CK_RV           PkcsStatus;
  CK_MECHANISM        PkcsMechanism = {0, NULL_PTR, 0};
  CK_OBJECT_HANDLE      hPkcsKey;
      
  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->ContextType != CSSM_ALGCLASS_SIGNATURE)
    return SetErr(CSSM_CSP_INVALID_CONTEXT_HANDLE);


  // Setting things up for init

  switch (pCssmContext->AlgorithmType)
  {
    case CSSM_ALGID_RSA_PKCS:
      PkcsMechanism.mechanism = CKM_RSA_PKCS;
      break;

    case CSSM_ALGID_RSA_ISO9796:
      PkcsMechanism.mechanism = CKM_RSA_9796;
      break;

    case CSSM_ALGID_RSA_RAW:
      PkcsMechanism.mechanism = CKM_RSA_X_509;
      break;

    case CSSM_ALGID_DSA:
      PkcsMechanism.mechanism = CKM_DSA;
      break;

#ifdef PKCS11_V20
    case CSSM_ALGID_FortezzaTimestamp:
      PkcsMechanism.mechanism = CKM_FORTEZZA_TIMESTAMP;
      break;

    case CSSM_ALGID_ECDSA:
      PkcsMechanism.mechanism = CKM_ECDSA;
      break;
#endif
  }


  // Get key

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

  pCssmKey = pCssmKeyAttr->Attribute.Key;

  if (pCssmKey->KeyHeader.BlobType == CSSM_KEYBLOB_REFERENCE &&
    pCssmKey->KeyHeader.Format == CSSM_KEYBLOB_REF_FORMAT_INTEGER &&
    pCssmKey->KeyHeader.KeyClass == CSSM_KEYCLASS_PRIVATE_KEY &&
    (pCssmKey->KeyHeader.AlgorithmId == CSSM_ALGID_RSA_PKCS ||
     pCssmKey->KeyHeader.AlgorithmId == CSSM_ALGID_RSA_ISO9796 ||
     pCssmKey->KeyHeader.AlgorithmId == CSSM_ALGID_RSA_RAW ||
     pCssmKey->KeyHeader.AlgorithmId == CSSM_ALGID_DSA ||
     pCssmKey->KeyHeader.AlgorithmId == CSSM_ALGID_FortezzaTimestamp ||
     pCssmKey->KeyHeader.AlgorithmId == CSSM_ALGID_ECDSA))
  {
    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);


  // Buffer checking and allocation 

  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);

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

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

  
  if (pCssmSignature->Data == NULL && pCssmSignature->Length == 0)
  {
    switch (pCssmContext->AlgorithmType)
    {
      case CSSM_ALGID_RSA_PKCS:
      case CSSM_ALGID_RSA_ISO9796:
      case CSSM_ALGID_RSA_RAW:
        pCssmSignature->Length = pCssmKey->KeyHeader.KeySizeInBits / BITSPERBYTE;
        if ((pCssmKey->KeyHeader.KeySizeInBits % BITSPERBYTE) != 0)
          pCssmSignature->Length++;
        break;

      case CSSM_ALGID_DSA:
      case CSSM_ALGID_FortezzaTimestamp:
      case CSSM_ALGID_ECDSA:
        pCssmSignature->Length = DSASIGLEN;
        break;
    }

    if ((pCssmSignature->Data = CssmMemFuncs.calloc_func(CssmCSPHandle, 
                               1,
                               pCssmSignature->Length)) == NULL)
      return SetErr(CSSM_CALLOC_FAILED);
  
    MsmBufferAllocated = CSSM_TRUE;
  }
  else if (pCssmSignature->Data != NULL)
  {
    switch (pCssmContext->AlgorithmType)
    {
      case CSSM_ALGID_RSA_PKCS:
      case CSSM_ALGID_RSA_ISO9796:
      case CSSM_ALGID_RSA_RAW:
        length = pCssmKey->KeyHeader.KeySizeInBits;
        if ((pCssmKey->KeyHeader.KeySizeInBits % BITSPERBYTE) != 0)
          length++;

        if (pCssmSignature->Length < length)
          return (CSSM_CSP_INVALID_PARAM_LENGTH);
        
        break;

      case CSSM_ALGID_DSA:
      case CSSM_ALGID_FortezzaTimestamp:
      case CSSM_ALGID_ECDSA:
        if (pCssmSignature->Length < DSASIGLEN)
          return (CSSM_CSP_INVALID_PARAM_LENGTH); ;
        break;
    }
  }


  // Now do the sign
#ifdef PKCS11_V20
  if ((PkcsStatus = C_Sign(pMsmSession->PkcsSessionHandle, 
               pCssmDataBufs->Data,
               pCssmDataBufs->Length,
               pCssmSignature->Data,
               &length)) != CKR_OK)
#else
  if ((PkcsStatus = C_Sign(pMsmSession->PkcsSessionHandle, 
               pCssmDataBufs->Data,
               (CK_USHORT)pCssmDataBufs->Length,
               pCssmSignature->Data,
               &length)) != CKR_OK)
#endif
  {
    if (MsmBufferAllocated)
    {
      CssmMemFuncs.free_func(CssmCSPHandle, pCssmSignature->Data);
      pCssmSignature->Length = 0;
      pCssmSignature->Data = NULL_PTR;
    }

    return SetErr(PkcsStatus);
  }

  pCssmSignature->Length = length;

  return CSSM_OK;

}


#ifdef PKCS11_V20

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

  CSSM_CONTEXT_ATTRIBUTE_PTR  pCssmKeyAttr;
  CSSM_KEY_PTR        pCssmKey;

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

  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_SIGNATURE)
    return SetErr(CSSM_CSP_INVALID_CONTEXT);


  // Setting things up for init

  switch (pCssmContext->AlgorithmType)
  {
#ifdef PKCS11_V20

    case CSSM_ALGID_MD2WithRSA:
      PkcsMechanism.mechanism = CKM_MD2_RSA_PKCS;
      break;

    case CSSM_ALGID_MD5WithRSA:
      PkcsMechanism.mechanism = CKM_MD5_RSA_PKCS;
      break;

    case CSSM_ALGID_SHA1WithRSA:
      PkcsMechanism.mechanism = CKM_SHA1_RSA_PKCS;
      break;

    case CSSM_ALGID_SHA1WithDSA:
      PkcsMechanism.mechanism = CKM_DSA_SHA1;
      break;
#endif
      
    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_PRIVATE_KEY &&
    (pCssmKey->KeyHeader.AlgorithmId == CSSM_ALGID_MD2WithRSA ||
     pCssmKey->KeyHeader.AlgorithmId == CSSM_ALGID_MD5WithRSA ||
     pCssmKey->KeyHeader.AlgorithmId == CSSM_ALGID_SHA1WithDSA) &&
     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: SignDataUpdate 
 * 
 * Update stage of sign operation.
 *
 * Input:
 *  CssmCSPHandle   - Attach session handle 
 *  CssmCCHandle    - Context handle
 *  pCssmDataBufs   - Data to be signed
 *  CssmDataBufCount  - Number of input buffers
 *   
 * Output:
 *  None
 *   
 * Returns:
 *  CSSM_OK       - Successful      
 *  CSSM_FAIL     - Failed
 *
 */

CSSM_RETURN CSSMAPI SignDataUpdate(
  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_SIGNATURE) 
    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);

  if ((PkcsStatus = C_SignUpdate(pMsmSession->PkcsSessionHandle,
                   pCssmDataBufs->Data, 
                   pCssmDataBufs->Length)) != CKR_OK)
    return SetErr(PkcsStatus);

  return CSSM_OK;

}



/*****************************************************************************
 * Function: SignDataFinal - Final stage of sign operation.
 *
 * Input:
 *  CssmCSPHandle   - Attach session handle 
 *  CssmCCHandle    - Context handle
 *   
 * Output:
 *  pCssmSignature    - Computed signature
 *   
 * Returns:
 *  CSSM_OK       - Successful      
 *  CSSM_FAIL     - Failed
 *
 */

CSSM_RETURN CSSMAPI SignDataFinal(
  CSSM_CSP_HANDLE CssmCSPHandle,
  CSSM_CC_HANDLE CssmCCHandle,
  CSSM_DATA_PTR pCssmSignature)
{

  CSSM_CONTEXT_PTR      pCssmContext;
  CSSM_CONTEXT_ATTRIBUTE_PTR  pCssmKeyAttr;
  CSSM_KEY_PTR        pCssmKey;

  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;

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


  pCssmKeyAttr = CSSM_GetContextAttribute(pCssmContext, CSSM_ATTRIBUTE_KEY);
  if (pCssmKeyAttr == NULL)
  {
    CSSM_FreeContext(pCssmContext);
    return SetErr(CSSM_CSP_PARAM_NO_KEY); 
  }

  pCssmKey = pCssmKeyAttr->Attribute.Key;


  // Buffer checking and allocation 

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

  if (pCssmSignature->Data == NULL && pCssmSignature->Length == 0)
  {

    switch (pCssmContext->AlgorithmType)
    {
      case CSSM_ALGID_MD2WithRSA:
      case CSSM_ALGID_MD5WithRSA:
      case CSSM_ALGID_SHA1WithRSA:
        pCssmSignature->Length = pCssmKey->KeyHeader.KeySizeInBits / BITSPERBYTE;
        if ((pCssmKey->KeyHeader.KeySizeInBits % BITSPERBYTE) != 0)
          pCssmSignature->Length++;
        break;

      case CSSM_ALGID_SHA1WithDSA:
        pCssmSignature->Length = DSASIGLEN;
        break;
      default:
        CSSM_FreeContext(pCssmContext); 
        return SetErr(CSSM_CSP_ALGORITHM_UNSUPPORTED);
    }

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

    MsmBufferAllocated = CSSM_TRUE;
  }
  

  // Now do the final
  if ((PkcsStatus = C_SignFinal(pMsmSession->PkcsSessionHandle, 
                  pCssmSignature->Data,
                  &pCssmSignature->Length)) != CKR_OK)
  {
    if (MsmBufferAllocated)
    {
      CssmMemFuncs.free_func(CssmCSPHandle,  pCssmSignature->Data);
      pCssmSignature->Length = 0;
      pCssmSignature->Data = NULL_PTR;
    }
    
    CSSM_FreeContext(pCssmContext); 
    return SetErr(PkcsStatus);
  }

  CSSM_FreeContext(pCssmContext); 
  return CSSM_OK;

}

#endif


/*****************************************************************************
 * Function: VerifyData 
 * 
 * Verify signed data.
 *
 * Input:
 *  CssmCSPHandle   - Attach session handle 
 *  CssmCCHandle    - Context handle
 *  pCssmContext    - Pointer to context 
 *  pCssmDataBufs   - Data to be verified
 *  CssmDataBufCount  - Number of input buffers
 *   
 * Output:
 *  pCssmSignature    - Computed signature
 *   
 * Returns:
 *  CSSM_OK       - Successful      
 *  CSSM_FAIL     - Failed
 *
 */

CSSM_BOOL CSSMAPI VerifyData(
  CSSM_CSP_HANDLE CssmCSPHandle,
  CSSM_CC_HANDLE CssmCCHandle,
  const CSSM_CONTEXT_PTR pCssmContext,
  const CSSM_DATA_PTR pCssmDataBufs,
  uint32 CssmDataBufCount,
  const CSSM_DATA_PTR pCssmSignature)
{
  switch (pCssmContext->AlgorithmType)
  {
    case CSSM_ALGID_RSA_PKCS:
    case CSSM_ALGID_RSA_ISO9796:
    case CSSM_ALGID_RSA_RAW:
    case CSSM_ALGID_DSA:
    case CSSM_ALGID_ECDSA:
    case CSSM_ALGID_FortezzaTimestamp:
      return VerifyDataSinglePart(CssmCSPHandle,
                    CssmCCHandle,
                    pCssmContext,
                    pCssmDataBufs,
                    CssmDataBufCount,
                    pCssmSignature);

#ifdef PKCS11_V20

    case CSSM_ALGID_MD2WithRSA:
    case CSSM_ALGID_MD5WithRSA:
    case CSSM_ALGID_SHA1WithRSA:
    case CSSM_ALGID_SHA1WithDSA:
      if (VerifyDataInit(CssmCSPHandle, CssmCCHandle, pCssmContext) != CSSM_OK)
        return CSSM_FALSE;
  
      if (VerifyDataUpdate(CssmCSPHandle, CssmCCHandle, pCssmDataBufs, CssmDataBufCount) != CSSM_OK)
        return CSSM_FALSE;

      return VerifyDataFinal(CssmCSPHandle, CssmCCHandle, pCssmSignature);
#endif

    default:
      return SetErr(CSSM_CSP_ALGORITHM_UNSUPPORTED);

  }
}
  



/*****************************************************************************
 * Function: VerifyDataSinglePart
 * 
 * Verify signed data in one stage.
 *
 * Input:
 *  CssmCSPHandle   - Attach session handle 
 *  CssmCCHandle    - Context handle
 *  pCssmContext    - Pointer to context 
 *  pCssmDataBufs   - Data to be verified
 *  CssmDataBufCount  - Number of input buffers
 *   
 * Output:
 *  pCssmSignature    - Computed signature
 *   
 * Returns:
 *  CSSM_OK       - Successful      
 *  CSSM_FAIL     - Failed
 *
 */

CSSM_BOOL CSSMAPI VerifyDataSinglePart(
  CSSM_CSP_HANDLE CssmCSPHandle,
  CSSM_CC_HANDLE CssmCCHandle,
  const CSSM_CONTEXT_PTR pCssmContext,
  const CSSM_DATA_PTR pCssmDataBufs,
  uint32 CssmDataBufCount,
  CSSM_DATA_PTR pCssmSignature)
{

  CSSM_CONTEXT_ATTRIBUTE_PTR  pCssmKeyAttr;
  CSSM_KEY_PTR        pCssmKey;

  CK_RV           PkcsStatus;
  CK_MECHANISM        PkcsMechanism = {0, NULL_PTR, 0};
  CK_OBJECT_HANDLE      hPkcsKey;
      
  MSMSESSION_PTR        pMsmSession;
  CSSM_BOOL         MsmBufferAllocated = CSSM_FALSE;




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

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

  // Setting things up for init

  switch (pCssmContext->AlgorithmType)
  {
    case CSSM_ALGID_RSA_PKCS:
      PkcsMechanism.mechanism = CKM_RSA_PKCS;
      break;

    case CSSM_ALGID_RSA_ISO9796:
      PkcsMechanism.mechanism = CKM_RSA_9796;
      break;

    case CSSM_ALGID_RSA_RAW:
      PkcsMechanism.mechanism = CKM_RSA_X_509;
      break;

    case CSSM_ALGID_DSA:
      PkcsMechanism.mechanism = CKM_DSA;
      break;

#ifdef PKCS11_V20
    case CSSM_ALGID_FortezzaTimestamp:
      PkcsMechanism.mechanism = CKM_FORTEZZA_TIMESTAMP;
      break;

    case CSSM_ALGID_ECDSA:
      PkcsMechanism.mechanism = CKM_ECDSA;
      break;
#endif
  }


  // Get key

  pCssmKeyAttr = CSSM_GetContextAttribute(pCssmContext, CSSM_ATTRIBUTE_KEY);
  if (pCssmKeyAttr == NULL)
    return SetErrFalse(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_PUBLIC_KEY &&
    (pCssmKey->KeyHeader.AlgorithmId == CSSM_ALGID_RSA_PKCS ||
     pCssmKey->KeyHeader.AlgorithmId == CSSM_ALGID_RSA_ISO9796 ||
     pCssmKey->KeyHeader.AlgorithmId == CSSM_ALGID_RSA_RAW ||
     pCssmKey->KeyHeader.AlgorithmId == CSSM_ALGID_DSA ||
     pCssmKey->KeyHeader.AlgorithmId == CSSM_ALGID_FortezzaTimestamp ||
     pCssmKey->KeyHeader.AlgorithmId == CSSM_ALGID_ECDSA))
  {
    if (pCssmKey->KeyData.Data == NULL)
      return SetErr(CSSM_CSP_INVALID_KEY_POINTER);

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


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


  // Buffer checking and allocation 

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

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

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

  if (pCssmSignature == NULL)
    return SetErrFalse(CSSM_CSP_INVALID_POINTER);

  if (pCssmSignature->Data == NULL || pCssmSignature->Length == 0)
    return SetErrFalse(CSSM_CSP_INVALID_DATA_POINTER);    


  // Now do the verify
#ifdef PKCS11_V20
  if ((PkcsStatus = C_Verify(pMsmSession->PkcsSessionHandle, 
               pCssmDataBufs->Data,
               pCssmDataBufs->Length,
               pCssmSignature->Data,
               pCssmSignature->Length)) != CKR_OK)
#else
  if ((PkcsStatus = C_Verify(pMsmSession->PkcsSessionHandle, 
               pCssmDataBufs->Data,
               (CK_USHORT) pCssmDataBufs->Length,
               pCssmSignature->Data,
               (CK_USHORT) pCssmSignature->Length)) != CKR_OK)
#endif
    return SetErr(PkcsStatus);

  return CSSM_TRUE;
}


#ifdef PKCS11_V20

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

  CSSM_CONTEXT_ATTRIBUTE_PTR  pCssmKeyAttr;
  CSSM_KEY_PTR        pCssmKey;

  CK_RV           PkcsStatus;
  CK_MECHANISM        PkcsMechanism  = {0, NULL_PTR, 0};
  CK_OBJECT_HANDLE      hPkcsKey;
      
  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_SIGNATURE)
    return SetErr(CSSM_CSP_INVALID_CONTEXT);

  // Setting things up for init

  switch (pCssmContext->AlgorithmType)
  {
    case CSSM_ALGID_MD2WithRSA:
      PkcsMechanism.mechanism = CKM_MD2_RSA_PKCS;
      break;

    case CSSM_ALGID_MD5WithRSA:
      PkcsMechanism.mechanism = CKM_MD5_RSA_PKCS;
      break;

    case CSSM_ALGID_SHA1WithRSA:
      PkcsMechanism.mechanism = CKM_SHA1_RSA_PKCS;
      break;

    case CSSM_ALGID_SHA1WithDSA:
      PkcsMechanism.mechanism = CKM_DSA_SHA1;
      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_PRIVATE_KEY &&
    (pCssmKey->KeyHeader.AlgorithmId == CSSM_ALGID_MD2WithRSA ||
     pCssmKey->KeyHeader.AlgorithmId == CSSM_ALGID_MD5WithRSA ||
     pCssmKey->KeyHeader.AlgorithmId == CSSM_ALGID_SHA1WithDSA) &&
     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: VerifyDataUpdate 
 * 
 * Update stage of verify operation.
 *
 * Input:
 *  CssmCSPHandle   - Attach session handle 
 *  CssmCCHandle    - Context handle
 *  pCssmDataBufs   - Data to be verified
 *  CssmDataBufCount  - Number of input buffers
 *   
 * Output:
 *  None
 *   
 * Returns:
 *  CSSM_OK       - Successful      
 *  CSSM_FAIL     - Failed
 *
 */

CSSM_RETURN CSSMAPI VerifyDataUpdate(
  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_SIGNATURE) 
    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);

  if ((PkcsStatus = C_VerifyUpdate(pMsmSession->PkcsSessionHandle,
                     pCssmDataBufs->Data, 
                     pCssmDataBufs->Length)) != CKR_OK)
    return SetErr(PkcsStatus);

  return CSSM_OK;

}



/*****************************************************************************
 * Function: VerifyDataFinal - Final stage of verify operation.
 *
 * Input:
 *  CssmCSPHandle   - Attach session handle 
 *  CssmCCHandle    - Context handle
 *  pCssmSignature    - Computed signature
 *
 * Output:
 *  None
 *   
 * Returns:
 *  CSSM_TRUE     - Successful            
 *  CSSM_FALSE      - Failed
 *
 */

CSSM_BOOL CSSMAPI VerifyDataFinal(
  CSSM_CSP_HANDLE CssmCSPHandle,
  CSSM_CC_HANDLE CssmCCHandle,
  const CSSM_DATA_PTR pCssmSignature)
{

  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_SIGNATURE) 
    return SetErr(CSSM_CSP_INVALID_CONTEXT);



  // Buffer checking  

  if (pCssmSignature == NULL)
    return SetErrFalse(CSSM_CSP_INVALID_POINTER);

  if (pCssmSignature->Data == NULL || pCssmSignature->Length == 0)
    return SetErrFalse(CSSM_CSP_INVALID_DATA_POINTER);    

  // Now do the final

  if ((PkcsStatus = C_VerifyFinal(pMsmSession->PkcsSessionHandle, 
                      pCssmSignature->Data,
                    pCssmSignature->Length)) != CKR_OK)
    return SetErrFalse(PkcsStatus);

  return CSSM_TRUE;
}

#endif
