/* -----------------------------------------------------------------------
 *
 * 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-cipher.h>
#include <include/ecctk-ecc.h>

s2byte generate_cipher()
{
	s4byte	ret		= -1;

	/* set symetric information
	 */
#ifndef ECCTK_EVALUATION
	u1byte	algo	= ECCTK_CIPHER_ALGO_RIJNDAEL,
#else
	u1byte	algo	= ECCTK_CIPHER_ALGO_BLOWFISH,
#endif
			mode		= ECCTK_CIPHER_MODE_OFB,
			compress	= ECCTK_COMPRESS_ON,
			*iv;

	/* set generic key and iv size for algorithm
	 */
	s2byte	keysize = CipherAlgorithmKeySize(algo),
			ivsize = CipherAlgorithmIVSize(algo);

	/* set input/output file name
	 */
	s1byte	cipherfile[] = "cipher_file";

	/* cipher context
	 */
	ECC_CIPHER_CTX *cipher;

	/* generate random iv (convert ivsize in byte to bits)
	 */
	iv = GenerateRandom(ivsize * 8);
	if (iv == NULL)
	{
		fprintf(stderr, "Generate random iv failed\n");
		return EXIT_FAILURE;
	}

	cipher = CreateEccCipherCtx(algo, mode, compress, keysize, ivsize, iv);
	if (cipher == NULL)
	{
		fprintf(stderr, "Create cipher context failed\n");

		free(iv);
		return EXIT_FAILURE;
	}

	/* free iv value, not used later
	 */
	free(iv);

	/* Save cipher context on file
	 */
	ret = WriteFileEccCipherCtx(cipherfile, cipher);
	if (ret != ECCTK_ECC_NO_ERROR)
	{
		fprintf(stderr, "Write cipher context on %s failed (Error : %ld)\n", cipherfile, ret);
		
		EccCipherCtxFree(cipher);
		return EXIT_FAILURE;
	}

	fprintf(stdout, "Create cipher context success\n");

	EccCipherCtxFree(cipher);

	return EXIT_SUCCESS;
}
