/* ***************************************************************** *
 * 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 "exception.hpp"
#include "cssmerr.h"
#include "misc.hpp"
#include "cipher.hpp"
#include "descipher.hpp"
#include "tdescipher.hpp"
#include "safercipher.hpp"

/**********************************************************
 *
 *	Cipher class
 *
 **********************************************************/
Cipher::Cipher(CSSM_CC_HANDLE ctxHandle, uint32 algId, uint32 mode)
:Context(ctxHandle, CSSM_ALGCLASS_SYMMETRIC, algId)
 {
	switch (algId) {
		case CSSM_ALGID_DES :
			engine = new DESCipherEngine(mode);
			break;
		case CSSM_ALGID_3DES:
		case CSSM_ALGID_3DES_3KEY:
		case CSSM_ALGID_3DES_2KEY:
		case CSSM_ALGID_3DES_1KEY:
			engine = new TDESCipherEngine(algId, mode);
			break;
		case CSSM_ALGID_SAFER:
			engine = new SAFERCipherEngine(mode);
			break;
		default:
			throw ParamException(CSSM_CSP_UNKNOWN_ALGORITHM);
			break;
	}
}

Cipher::~Cipher() {
	if (engine != NULL) delete engine;
}

void Cipher::encryptInit(Key *key, void *params) {
	engine->encryptInit(key, params);
}

void Cipher::encryptUpdate(CSSM_DATA_PTR clearBuff, uint32 clearBuffCount,
				   CSSM_DATA_PTR cipherBuff, uint32 cipherBuffCount,
				   uint32 *bytesEncrypted)
{
	//multiple buffers are not supported -> no semantics defined
	if ((clearBuffCount != 1) || (cipherBuffCount != 1))
		throw InputException(CSSM_CSP_PARAM_INVALID_VALUE);

	if ((clearBuff == NULL) || (clearBuff->Data == NULL))
		throw InputException(CSSM_CSP_INPUT_DATA_ERROR);

	if (clearBuff->Length == 0)
		throw InputException(CSSM_CSP_ERR_INBUF_LENGTH);

	if (bytesEncrypted == NULL)
		throw InputException(CSSM_CSP_INVALID_POINTER);

	if ((cipherBuff == NULL) ||
		((cipherBuff->Data == NULL) && (getCipherTextLength(clearBuff->Length) != 0)))
	/* We cannot simply check for a ->Data NULL pointer, because in some cases this
	 * might be ok (if the input and the rem data do not make up for a full block. */
		throw InputException(CSSM_CSP_NO_OUTBUF);
	
	if (cipherBuff->Length < getCipherTextLength(clearBuff->Length))
		throw InputException(CSSM_CSP_ERR_OUTBUF_LENGTH);

	CssmData clearBuffIn = CssmData(clearBuff);
	CssmData cipherBuffOut = CssmData(cipherBuff);

	engine->encryptUpdate(clearBuffIn, cipherBuffOut, bytesEncrypted);

	if (cipherBuff->Data != NULL)
		memcpy(cipherBuff->Data, cipherBuffOut.getData(), cipherBuffOut.getLength());
	cipherBuff->Length = cipherBuffOut.getLength();
}

void Cipher::encryptUpdate(CssmData *clearBuff, uint32 clearBuffCount,
				   CssmData *cipherBuff, uint32 cipherBuffCount,
				   uint32 *bytesEncrypted)
{
	//multiple buffers are not supported -> no semantics defined
	if ((clearBuffCount != 1) || (cipherBuffCount != 1)) 
		throw InputException(CSSM_CSP_PARAM_INVALID_VALUE);

	if ((clearBuff == NULL) || (clearBuff->getLength() == 0))
		throw InputException(CSSM_CSP_INPUT_DATA_ERROR);
		
	if (bytesEncrypted == NULL)
		throw InputException(CSSM_CSP_INVALID_POINTER);

	if (cipherBuff == NULL)
		throw InputException(CSSM_CSP_NO_OUTBUF);

	if (cipherBuff->getLength() < getCipherTextLength(clearBuff->getLength()))
		throw InputException(CSSM_CSP_ERR_OUTBUF_LENGTH);

	engine->encryptUpdate(*clearBuff, *cipherBuff, bytesEncrypted);
}

void Cipher::encryptFinal(CSSM_DATA_PTR remData) {
	//it might be OK for the remData->Data to be NULL, if there is no padding required
	if (remData == NULL)
		throw InputException(CSSM_CSP_INPUT_DATA_ERROR);

	//this will throw an exceptions if Data and Length of remData are not synchronized
	//(i.e., if Data is NULL and Length != 0, and so on)
	CssmData dataIn = CssmData(remData);

	engine->encryptFinal(dataIn);
	if (remData->Data == NULL) {
		//if this is true, and no exception was thrown, then it means
		//that there was no remaining data
		remData->Length = 0;
		return;
	}

	if (dataIn.getData() == NULL) {
		//thiw would happen if remData had some space allocated, but 
		//there was no remaining data
		/*remData->Data == NULL; <- if I do that, I will have a memory leak;*/
	}
	else {
		memcpy(remData->Data, dataIn.getData(), remData->Length);
	}
	remData->Length = dataIn.getLength();
}

void Cipher::encryptFinal(CssmData &remData) {
	engine->encryptFinal(remData);
}

void Cipher::encrypt(Key *key, void *params,
				   CSSM_DATA_PTR clearBuff, uint32 clearBuffCount,
				   CSSM_DATA_PTR cipherBuff, uint32 cipherBuffCount,
				   uint32 *bytesEncrypted, CSSM_DATA_PTR remData) {
	encryptInit(key, params);
	encryptUpdate(clearBuff, clearBuffCount, cipherBuff, cipherBuffCount, bytesEncrypted);
	encryptFinal(remData);
}

void Cipher::encrypt(Key *key, void *params,
				   CssmData *clearBuff, uint32 clearBuffCount,
				   CssmData *cipherBuff, uint32 cipherBuffCount,
				   uint32 *bytesEncrypted, CssmData &remData) {
	encryptInit(key, params);
	encryptUpdate(clearBuff, clearBuffCount, cipherBuff, cipherBuffCount, bytesEncrypted);
	encryptFinal(remData);
}

void Cipher::decryptInit(Key *key, void *params) {
		engine->decryptInit(key, params);
}

void Cipher::decryptUpdate(CSSM_DATA_PTR cipherBuff, uint32 cipherBuffCount,
				   CSSM_DATA_PTR clearBuff, uint32 clearBuffCount,
				   uint32 *bytesDecrypted) 
{
	//multiple buffers are not supported -> no semantics is defined
	if ((clearBuffCount != 1) || (cipherBuffCount != 1))
		throw InputException(CSSM_CSP_PARAM_INVALID_VALUE);

	if ((cipherBuff == NULL) ||(cipherBuff->Data == NULL))
		throw InputException(CSSM_CSP_INPUT_DATA_ERROR);

	if (cipherBuff->Length == 0)
		throw InputException(CSSM_CSP_ERR_INBUF_LENGTH);

	if (bytesDecrypted == NULL)
		throw InputException(CSSM_CSP_INVALID_POINTER);
	
	if ((clearBuff == NULL) ||
		((clearBuff->Data == NULL) && (getClearTextLength(cipherBuff->Length) != 0)))
	/* We cannot simply check for a ->Data NULL pointer, because in some cases this
	 * might be ok (if the input and the rem data do not make up for a full block. */
		throw InputException(CSSM_CSP_NO_OUTBUF);

	if (clearBuff->Length < getClearTextLength(cipherBuff->Length))
		throw InputException(CSSM_CSP_ERR_OUTBUF_LENGTH);

	CssmData cipherBuffIn = CssmData(cipherBuff);
	CssmData clearBuffOut = CssmData(clearBuff);

	engine->decryptUpdate(cipherBuffIn, clearBuffOut, bytesDecrypted);

	clearBuff->Length = clearBuffOut.getLength();
	if (clearBuff->Length == 0)
		clearBuff->Data = NULL;
	else
		memcpy(clearBuff->Data, clearBuffOut.getData(), clearBuffOut.getLength());
}

void Cipher::decryptUpdate(CssmData *cipherBuff, uint32 cipherBuffCount,
				   CssmData *clearBuff, uint32 clearBuffCount,
				   uint32 *bytesDecrypted) 
{
	//multiple buffers are not supported -> no semantics defined
	if ((clearBuffCount != 1) || (cipherBuffCount != 1))
		throw InputException(CSSM_CSP_PARAM_INVALID_VALUE);

	if ((cipherBuff == NULL) ||(cipherBuff->getLength() == 0))
		throw InputException(CSSM_CSP_INPUT_DATA_ERROR);

	if (bytesDecrypted == NULL)
		throw InputException(CSSM_CSP_INVALID_POINTER);

	if (clearBuff == NULL)
		throw InputException(CSSM_CSP_NO_OUTBUF);

	if (clearBuff->getLength() < getClearTextLength(cipherBuff->getLength()))
		throw InputException(CSSM_CSP_ERR_OUTBUF_LENGTH);

	engine->decryptUpdate(*cipherBuff, *clearBuff, bytesDecrypted);
}

void Cipher::decryptFinal(CSSM_DATA_PTR remData) {
	//it might be OK for the remData->Data to be NULL, if there is no padding required
	if (remData == NULL)
		throw InputException(CSSM_CSP_INPUT_DATA_ERROR);

	//this will throw an exceptions if Data and Length of remData are not synchronized
	//(i.e., if Data is NULL and Length != 0, and so on)
	CssmData dataIn = CssmData(remData);

	engine->decryptFinal(dataIn);
	if (remData->Data == NULL) {
		//if this is true, and no exception was thrown, then it means
		//that there was no remaining data
		remData->Length = 0;
		return;
	}

	if (dataIn.getLength() == 0) {
		//thiw would happen if remData had some space allocated, but 
		//there was no remaining data
		/*remData->Data == NULL; <- if I do that, I will have a memory leak;*/
	}
	else {
		memcpy(remData->Data, dataIn.getData(), remData->Length);
	}
	remData->Length = dataIn.getLength();
}

void Cipher::decryptFinal(CssmData &remData) {
	engine->decryptFinal(remData);
}

void Cipher::decrypt(Key *key, void *params, CSSM_DATA_PTR cipherBuff, uint32 cipherBuffCount,
					   CSSM_DATA_PTR clearBuff, uint32 clearBuffCount,
					   uint32 *bytesDecrypted, CSSM_DATA_PTR remData)
{
	decryptInit(key, params);
	decryptUpdate(cipherBuff, cipherBuffCount, clearBuff, clearBuffCount, bytesDecrypted);
	decryptFinal(remData);
}

void Cipher::decrypt(Key *key, void *params, CssmData* cipherBuff, uint32 cipherBuffCount,
					   CssmData* clearBuff, uint32 clearBuffCount,
					   uint32 *bytesDecrypted, CssmData &remData)
{
	decryptInit(key, params);
	decryptUpdate(cipherBuff, cipherBuffCount, clearBuff, clearBuffCount, bytesDecrypted);
	decryptFinal(remData);
}

uint32 Cipher::getCipherTextLength(uint32 ClearTextLength) {
	return(engine->getCipherTextLength(ClearTextLength));
}

uint32 Cipher::getCipherRemLength(uint32 ClearTextLength) {
	return(engine->getCipherRemLength(ClearTextLength));
}

uint32 Cipher::getCipherMaxRemLength() {
	return(engine->getCipherMaxRemLength());
}

uint32 Cipher::getClearTextLength(uint32 CipherTextLength) {
	return(engine->getClearTextLength(CipherTextLength));
}

uint32 Cipher::getClearRemLength(uint32 CipherTextLength) {
	return(engine->getClearRemLength(CipherTextLength));
}

uint32 Cipher::getClearMaxRemLength() {
	return(engine->getClearMaxRemLength());
}

uint32 Cipher::getMode() {
	return(mode);
}

/**********************************************************
 *
 *	CipherEngine class
 *
 **********************************************************/
CipherEngine::CipherEngine(uint32 algId, uint32 mode) {
	this->algId = algId;
	this->mode = mode;
}

CipherEngine::~CipherEngine() {
}
