/* -----------------------------------------------------------------------
 *
 * Copyright (c) 2002-2005 Mr Ludovic FLAMENT <ludovic.flament@free.fr>, LIEVIN, 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 encrypt_file_asym()
{
	s4byte	ret		= -1;

	/* set algo
	 */
	s2byte	algo	= ECCTK_ECC_ALGO_PSEC3;

	/* set hash & hmac algorithm
	 */
#ifndef ECCTK_EVALUATION
	s2byte	hash_algo = ECCTK_HASH_ALGO_SHA384,
#else
	s2byte	hash_algo = ECCTK_HASH_ALGO_SHA160,
#endif
			hmac_algo = ECCTK_HASH_HMAC_ALGO_SHA160;	

	/* set input/output file name
	 */
	s1byte	infile[]	= "protected_file",
			outfile[]	= "unprotected_file",
			kpubfile[]	= "public_key_file",
			cipherfile[]= "cipher_file";

	/* public key context
	 */
	KPUB_CTX *kpub;

	/* cipher context
	 */
	ECC_CIPHER_CTX *cipher;

	/* read public key on file
	 */
	kpub = ReadFileKpubCtx(kpubfile);
	if (kpub == NULL)
	{
		fprintf(stderr, "Read public key on %s failed\n", kpubfile);
		return EXIT_FAILURE;
	}

	/* read cipher context on file
	 */
	cipher = ReadFileEccCipherCtx(cipherfile);
	if (cipher == NULL)
	{
		fprintf(stderr, "Read cipher on %s failed\n", cipherfile);
		KpubCtxFree(kpub);
		return EXIT_FAILURE;
	}

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

	switch (algo)
	{
	case ECCTK_ECC_ALGO_ECIES:
		ret = EncryptFileEcies(infile, outfile, hmac_algo, kpub, cipher);
		break;
	case ECCTK_ECC_ALGO_PSEC3:
		ret = EncryptFilePsec3(infile, outfile, hash_algo, kpub, cipher);
		break;
	default:
		ret = -1;
		break;
	}

	if (ret != ECCTK_ECC_NO_ERROR)
		fprintf(stderr, "Encrypt %s failed (Error : %ld)\n", infile, ret);
	else
		fprintf(stdout, "Encrypt %s success, %s generated\n", infile, outfile);

	/* free context
	 */
	KpubCtxFree(kpub);
	EccCipherCtxFree(cipher);

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

	return EXIT_SUCCESS;
}
