/*
 * Copyright (c) 2000-2001 Apple Computer, Inc. All Rights Reserved.
 * 
 * The contents of this file constitute Original Code as defined in and are
 * subject to the Apple Public Source License Version 1.2 (the 'License').
 * You may not use this file except in compliance with the License. Please obtain
 * a copy of the License at http://www.apple.com/publicsource and read it before
 * using this file.
 * 
 * This Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS
 * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT
 * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
 * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the
 * specific language governing rights and limitations under the License.
 */


/*
 * FEECSPUtils.h - Misc. utility function for FEE/CryptKit CSP. 
 *
 * Created 2/20/2001 by dmitch.
 */

#ifdef	CRYPTKIT_CSP_ENABLE
 
#ifndef	_FEE_CSP_UTILS_H_
#define _FEE_CSP_UTILS_H_

#include "AppleCSPSession.h"
#include <CryptKit/feeTypes.h>
#include <Security/context.h>

/*
 * Default FEE keyblob format, indicating DER-encoding.
 * FEE keys can optionally be generated by requesting 
 * CSSM_KEYBLOB_RAW_FORMAT_OCTET_STRING, indicating native FEE key blobs.
 */
#define FEE_KEYBLOB_DEFAULT_FORMAT	CSSM_KEYBLOB_RAW_FORMAT_NONE

namespace CryptKit {

/* Given a FEE error, throw appropriate CssmError */
void throwCryptKit(
	feeReturn 	frtn, 
	const char	*op);		/* optional */

/* 
 * Given a Context:
 * -- obtain CSSM key of specified CSSM_ATTRIBUTE_TYPE
 * -- validate keyClass
 * -- validate keyUsage
 * -- convert to feePubKey, allocating the feePubKey if necessary
 */
feePubKey contextToFeeKey(
	const Context 		&context,
	AppleCSPSession	 	&session,
	CSSM_ATTRIBUTE_TYPE	attrType,	  // CSSM_ATTRIBUTE_KEY, CSSM_ATTRIBUTE_PUBLIC_KEY
	CSSM_KEYCLASS		keyClass,	  // CSSM_KEYCLASS_{PUBLIC,PRIVATE}_KEY
	CSSM_KEYUSE			usage,		  // CSSM_KEYUSE_ENCRYPT, CSSM_KEYUSE_SIGN, etc.
	bool				&mallocdKey); // RETURNED

/* 
 * Convert a CssmKey to a feePubKey. May result in the creation of a new
 * feePubKey (when cssmKey is a raw key); allocdKey is true in that case
 * in which case the caller generally has to free the allocd key).
 */
feePubKey cssmKeyToFee(
	const CssmKey	&cssmKey,
	AppleCSPSession	&session,
	bool			&allocdKey);	// RETURNED

/* 
 * Convert a raw CssmKey to a newly alloc'd feePubKey.
 */
feePubKey rawCssmKeyToFee(
	const CssmKey	&cssmKey);

/*
 * Glue function which allows C code to use AppleCSPSession 
 * as an RNG. A ptr to this function gets passed down to 
 * CryptKit C functions as a feeRandFcn.
 */
feeReturn feeRandCallback(
	void 			*ref,		// actually an AppleCSPSession *
	unsigned char 	*bytes,		// must be alloc'd by caller 
	unsigned 		numBytes);

} /* namespace CryptKit */

#endif	/* _FEE_CSP_UTILS_H_ */
#endif	/* CRYPTKIT_CSP_ENABLE */
