/* ***************************************************************** *
 * 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 "dsasign.hpp"
#include "ibmcylinkcsp.hpp"
#include "random.hpp"

/**********************************************************
 *
 *	DSASignEngine class
 *
 **********************************************************/
DSASignEngine::DSASignEngine()
: SignEngine(CSSM_ALGID_DSA)
{
	x.setDestroy(CSSM_TRUE);
	y.setDestroy(CSSM_TRUE);
	digest = new Digest(0, CSSM_ALGID_SHA1);
	randSource = new Random(0, CSSM_ALGID_SHARandom);
	signParams = NULL;
	verifyParams = NULL;
}

DSASignEngine::~DSASignEngine() {
	x.setLength(0);
	y.setLength(0);
	if (digest != NULL) delete digest;
	if (randSource != NULL) delete randSource;
	if (signParams != NULL) delete signParams;
	if (verifyParams != NULL) delete verifyParams;
}

void DSASignEngine::signInit(Key *key, void *params) {
	DSAParams*	tmpParams;
	KeyMaterial *keyMat = NULL;

	//store x, the private key
	keyMat = key->exportKeyMat();
	if (keyMat == NULL)
		throw InputException(CSSM_CSP_INVALID_KEY_POINTER);
			
	try {
		if (keyMat->getAlgId() != CSSM_ALGID_DSA)
			throw InputException(CSSM_CSP_KEY_ALGID_NOTMATCH);
			
		if (keyMat->getKeyClass() != CSSM_KEYCLASS_PRIVATE_KEY)
			throw InputException(CSSM_CSP_KEY_CLASS_INCORRECT);
		
		CssmData &tmpX = ((DSAPrivateKey *)keyMat)->getX();

		this->x.setData(tmpX.getLength(), tmpX.getData());
		delete &tmpX;

		//get DSAParams (p, q and g)
		tmpParams = ((DSAPrivateKey *)keyMat)->getParams();

		if (tmpParams == NULL)
			throw InputException(CSSM_CSP_KEY_BAD_KEY);
	} catch (...) {
		delete keyMat;
		throw;
	}
	
	delete keyMat;

	if (signParams != NULL)
		delete signParams;

	this->signParams = tmpParams;

	//initialize digest and objects
	digest->digestInit();
}

void DSASignEngine::signUpdate(CssmData &dataBuff) {
	digest->digestUpdate(&dataBuff, 1);
}

void DSASignEngine::signFinal(CssmData &signature) {
	CssmData		k = CssmData(SHA_LENGTH);
	uchar			randNum[SHA_LENGTH], r[SHA_LENGTH], s[SHA_LENGTH];
	uint32			rc;

	if (signature.getLength() < getSignatureLength())
		throw InputException(CSSM_CSP_ERR_OUTBUF_LENGTH);
		
	CssmData digestBuff = CssmData(digest->getDigestLength());
	digest->digestFinal(digestBuff);

	//get DSA parameters
	CssmData &p = signParams->getP();
	CssmData &q = signParams->getQ();
	CssmData &g = signParams->getG();

	//generate a random number
	randSource->generateRandom(k);
	memcpy(randNum, k.getData(), SHA_LENGTH);
	
	//generate per-message secret number k
	rc = GenDSSNumber(k.getData(), q.getData(), randNum);
	if (rc != SUCCESS) {
		delete &p;
		delete &q;
		delete &g;
		throw CryptoLibException(CSSM_CSP_SIGN_FINAL_FAILED);
	}

	rc = GenDSSSignature(p.getLength(), p.getData(), 
						 q.getData(), g.getData(),
						 x.getData(), k.getData(),
						 r, s,
						 digestBuff.getData());

	delete &p;
	delete &q;
	delete &g;

	if (rc != SUCCESS)
		throw CryptoLibException(CSSM_CSP_SIGN_FINAL_FAILED);

	memcpy(signature.getData(), r, SHA_LENGTH);
	memcpy(signature.getData() + SHA_LENGTH, s, SHA_LENGTH);
}

void DSASignEngine::verifyInit(Key *key, void *params) {
	DSAParams	*tmpParams;
	KeyMaterial *keyMat = NULL;

	//store y, the public key
	keyMat = key->exportKeyMat();

	if (keyMat == NULL)
		throw InputException(CSSM_CSP_KEY_BAD_KEY);

	try {
		if (keyMat->getAlgId() != CSSM_ALGID_DSA)
			throw InputException(CSSM_CSP_KEY_ALGID_NOTMATCH);

		CssmData &tmpY = ((DSAPublicKey *)keyMat)->getY();

		this->y.setData(tmpY.getLength(), tmpY.getData());
		delete &tmpY;

		//get DSAParams (p, q and g)
		tmpParams = ((DSAPublicKey *)keyMat)->getParams();
		if (tmpParams == NULL)
			throw InputException(CSSM_CSP_KEY_BAD_KEY);
	} catch (...) {
		delete keyMat;
		throw;
	}

	delete keyMat;

	if (verifyParams != NULL)
		delete verifyParams;

	this->verifyParams = tmpParams;

	//initialize digest object
	digest->digestInit();
}

void DSASignEngine::verifyUpdate(CssmData &dataBuff) {
	digest->digestUpdate(&dataBuff, 1);
}

CSSM_BOOL DSASignEngine::verifyFinal(CssmData &signature) {
	CssmData	digestBuff = CssmData(digest->getDigestLength());
	uint32		rc;

	if (signature.getLength() < getSignatureLength())
		throw InputException(CSSM_CSP_INPUT_LENGTH_ERROR);

	digest->digestFinal(digestBuff);

	CssmData &p = verifyParams->getP();
	CssmData &q = verifyParams->getQ();
	CssmData &g = verifyParams->getG();

	rc = VerDSSSignature(p.getLength(), p.getData(),
						 q.getData(), g.getData(),
						 y.getData(),
						 signature.getData(),
						 signature.getData() + SHA_LENGTH,
						 digestBuff.getData());

	delete &p;
	delete &q;
	delete &g;

	if (rc != SUCCESS) {
		if (rc == ERR_SIGNATURE) {
			return CSSM_FALSE;
		}
		throw CryptoLibException(CSSM_CSP_VERIFY_FINAL_FAILED);
	}

	return(CSSM_TRUE);
}

uint32 DSASignEngine::getSignatureLength() {
	return(2 * SHA_LENGTH);
}
