/* -----------------------------------------------------------------------
 *
 * Copyright (c) 2008 EURL Cryptographie Ingénierie et Conseil <ecctk@cryptograph-ic.com>, AIX-NOULETTE, FRANCE
 *
 * Termes :
 *
 * L'utilisation et/ou la redistribution de ce code (avec ou sans modification),
 * ainsi que de tous les composants du produit (librairies, documentation, exemples, ...)
 * est soumise aux termes de la licence qui vous est attribuée par son auteur.
 *
 * -----------------------------------------------------------------------
 */

#include <stdlib.h>
#include <stdio.h>

#include <include/ecctk-prototype.h>
#include <include/ecctk-hash.h>
#include <include/ecctk-ecc.h>

s2byte sign_file()
{
	s4byte	ret		= -1;

	/* set algo
	 */
	s2byte	algo	= ECCTK_ECC_ALGO_ECDSA;

	/* set hashalgorithm
	 */
	s2byte	hash_algo = ECCTK_HASH_ALGO_SHA160;

	/* set input/output file name
	 */
	s1byte	infile[]	= "protected_file",
			kprvfile[]	= "private_key_file",
			signfile[]	= "signature_file";

	/* private key context
	 */
	KPRV_CTX *kprv;

	/* signature context
	 */
	SIGN_CTX *sign;

	/* read private key on file (protected by password : "mypassword")
	 */
	kprv = ReadFileKprvCtx(kprvfile);
	if (kprv == NULL)
	{
		fprintf(stderr, "Read private key on %s failed\n", kprvfile);
		return EXIT_FAILURE;
	}

	/* Initialize value for all curve in memory
	 */
	ret = InitializeEcctkAll();
	if (ret != ECCTK_ECC_NO_ERROR)
	{
		fprintf(stderr, "InitializeEcctkAll failed (%ld)\n", ret);
		return EXIT_FAILURE;
	}

	switch (algo)
	{
	case ECCTK_ECC_ALGO_ECDSA:
		sign = SignFileEcdsa(infile, hash_algo, kprv, "mypassword");
		break;
	case ECCTK_ECC_ALGO_ECNR:
		sign = SignFileEcnr(infile, hash_algo, kprv, "mypassword");
		break;
	default:
		sign = NULL;
		break;
	}

	if (sign == NULL)
	{
		fprintf(stderr, "Sign %s failed\n", infile);

		/* remove value for all curve in memory
		*/
		FreeEcctkAll();

		KprvCtxFree(kprv);
		return EXIT_FAILURE;
	}

	/* write signature context on file
	 */
	ret = WriteFileSignCtx(signfile, sign);
	if (ret != ECCTK_ECC_NO_ERROR)
	{
		fprintf(stderr, "Write signature context on file %s failed (Error : %ld)\n", signfile, ret);
		
		/* remove value for all curve in memory
		*/
		FreeEcctkAll();

		KprvCtxFree(kprv);
		SignCtxFree(sign);
		return EXIT_FAILURE;
	}

	/* free context
	 */
	KprvCtxFree(kprv);
	SignCtxFree(sign);

	/* remove value for all curve in memory
	 */
	FreeEcctkAll();

	fprintf(stdout, "Sign %s success\n", infile);
	return EXIT_SUCCESS;
}

