#include "aes.h"

#include <string.h>

static aes_context ctx1;
static int initialised = 0;
static int count = 0;
unsigned char block[16];
unsigned char out[16];

/* block cyphers in "CTR" mode (counter mode) -
 * let's hope i got it right(!) - apparently make good PRNGs.
 */

static void init_ctx(void)
{
	static unsigned char key1[16];
	int i;
	for (i = 0; i < 16; i++)
		key1[i] = i*7+0x5a;
	aes_set_key( &ctx1, key1, 128 );
	memset(block, 0, 16);
	memset(out, 0, 16);
}

int gen_rand_impl(char *buf, unsigned int len)
{
	unsigned int i;
	if (!initialised)
	{
		init_ctx();
		initialised = 1;

		memset( block, 0, 16 );
	}
	for (i = 0; i < len; i += 16)
	{
		/*(int*)(&block[0]) = ++count;
		*(int*)(&block[4]) = ++count;
		*(int*)(&block[8]) = ++count;
		*(int*)(&block[12]) = ++count;*/
		int to_copy = 16;

		if (len - i < 16)
			to_copy = len - i;

		aes_encrypt( &ctx1, block, out );
		memcpy(buf, out, to_copy);
		for (i = 0; i < 16; i++)
			block[i] ^= out[i];
	}
	return 1;
}

