/* ***************************************************************** *
 * 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;
extern CSSM_GUID CssmGuid;

/*****************************************************************************
 * Function: C_ExtractClearKeyObject 
 *
 * This function creates a session key object on a Fips40 token  
 *
 * Input:
 *  hSession      - PKCS11 session handle
 *  phRefKey      - Pointer a key in native format
 *  pClearData      - Pointer to location to receive clear key data
 *
 * Output:
 *  pClearData      - Clear key data
 *
 * Returns:
 *  CKR_OK        - Successful      
 *  CKR_XXX       - See PKCS11 Document
 *
 */

#ifdef PKCS11_V20
CK_RV CK_ENTRY C_ExtractClearKeyObject(
  CK_SESSION_HANDLE hSession,
  CK_OBJECT_HANDLE_PTR phRefKey,    
  CSSM_DATA_PTR pClearKeyData,
  uint32 hCSP)
#else
CK_RV CK_ENTRY C_ExtractClearKeyObject(
  CK_SESSION_HANDLE hSession,
  CK_OBJECT_HANDLE_PTR phRefKey,
  CSSM_DATA_PTR pClearKeyData,
  uint32 hCSP)
#endif
{
#define MAX_KEY_LEN   RC4MAXKEYLEN
  CK_RV       rc, rc1;
  CK_MECHANISM    mech;
  CK_OBJECT_HANDLE  hWrappingKey;
  CK_OBJECT_CLASS   keyClass  = CKO_SECRET_KEY;
  CK_KEY_TYPE     keyType = CKK_DES;
  CK_BBOOL      bToken = FALSE;   
  CK_BBOOL            bSensitive = TRUE;
  CK_BBOOL      bPrivate = TRUE;
  CK_BBOOL      bEncrypt = TRUE;
  CK_BBOOL      bDecrypt = TRUE;
  CK_BBOOL      bWrap = TRUE;
  CK_BBOOL      bUnwrap = TRUE;

  CK_BYTE_PTR     wrappedKey = NULL_PTR;
  CK_BYTE_PTR     pDecryptedKeyData = NULL_PTR;
#ifdef PKCS11_V20
  CK_ULONG      decryptedKeyDataLen;
  CK_ULONG      wrappedKeyLen;
#else
  CK_USHORT     decryptedKeyDataLen;
  CK_USHORT     wrappedKeyLen;
#endif
   
   
  CK_ATTRIBUTE keyTemplate[] = {
    {CKA_CLASS, &keyClass, sizeof(keyClass)},
    {CKA_KEY_TYPE, &keyType, sizeof(keyType)},
    {CKA_TOKEN, &bToken, sizeof(bToken)},
    {CKA_SENSITIVE, &bSensitive, sizeof(bSensitive)},
    {CKA_PRIVATE, &bPrivate, sizeof(bPrivate)},
    {CKA_ENCRYPT, &bEncrypt, sizeof(bEncrypt)},
    {CKA_DECRYPT, &bDecrypt, sizeof(bDecrypt)},
    {CKA_WRAP, &bWrap, sizeof(bWrap)},
    {CKA_UNWRAP, &bUnwrap, sizeof(bUnwrap)}
  };
   

  mech.mechanism = CKM_DES_KEY_GEN;
  mech.pParameter = NULL_PTR;
#ifdef PKCS11_V20
  mech.ulParameterLen = 0;
#else
  mech.usParameterLen = 0;
#endif
   
  // wrapping key
    rc = C_GenerateKey(hSession,
                       &mech,
                       keyTemplate,
                       sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE),
                       &hWrappingKey);
  
  if (rc != CKR_OK)
    return rc;
    
  do {
    mech.mechanism = CKM_DES_ECB;

    wrappedKey = (CK_BYTE_PTR) malloc (MAX_KEY_LEN);

    rc = C_WrapKey(hSession, 
        &mech,
        hWrappingKey,
        *phRefKey,
        wrappedKey,
        &wrappedKeyLen);

    if (rc != CKR_OK)
      break;

    rc = C_DecryptInit(hSession,
        &mech,
        hWrappingKey);

    if (rc != CKR_OK)
      break;

    decryptedKeyDataLen = MAX_KEY_LEN;  

    if ((pDecryptedKeyData = CssmMemFuncs.calloc_func(hCSP, 1, decryptedKeyDataLen)) == NULL)  
    {
      rc = CKR_HOST_MEMORY;
      break;
    }

    rc = C_Decrypt(hSession, 
             wrappedKey,
             wrappedKeyLen,
             pDecryptedKeyData,
             &decryptedKeyDataLen);
             
  } while (0);
  
  rc1 = C_DestroyObject(hSession, hWrappingKey);

  free(wrappedKey);
  
  if (rc == CKR_OK)
  {
    pClearKeyData->Length = decryptedKeyDataLen;
    pClearKeyData->Data = pDecryptedKeyData;
  }
  else
  {
    memset(pClearKeyData, 0, sizeof(CSSM_DATA));
  }

  return rc;
}


