/*
 * Copyright (c) 1996-2007, OpenFWTK Development Group
 * All rights reserved. See LICENSE.
 */

static	char	RcsId[] = "";

#include <stdio.h>
#include <time.h>

extern	long	random();

#include	"des.h"

/*
	This is a simple hack to produce pretty random shared
	secrets for Digital Pathways SNK units.
*/

main()
{
	char			buf[MAX_STR];
	des_key_schedule	keysched;
	des_cblock		cblock;
	char			cbuf[12];
	int			seed;
	int			i;
	int			j;
	long			now;
	long			quad1;
	long			quad2;
	unsigned char		*p1;
	unsigned char		*p2;
	unsigned long		kval = 0;

	/* generate a seed from user typomatic */
	fprintf(stderr,"Enter a line of text as a seed: ");
	fgets(buf,sizeof(buf),stdin);
	des_string_to_key(buf,cblock);
	des_set_key(cblock,keysched);
	des_ecb_encrypt(buf,cbuf,keysched,DES_ENCRYPT);

	/* stuff raw cipherstuff into the seed */
	bcopy(cbuf,&seed,sizeof(int));
	time(&now);
	srandom(seed ^ (int)now);

	/* that should satisfy casual users */
	quad1 = random();
	quad2 = random();
	p1 = (unsigned char *)&quad1;
	p2 = (unsigned char *)&quad2;

	/* set up key using generated octets */
	for(i = 0; i < 4; i++) {
		cblock[i] = p1[i];
		cblock[i+4] = p2[i];
	}
	des_set_key(cblock,keysched);
	for(i = 0; i < 9; i++)
		buf[i] = '\0';
	des_ecb_encrypt(buf,cbuf,keysched,DES_ENCRYPT);
	/* pull bits into a long */
	for(i=0; i < 4; i++)
		for(j = 0; j < 8; j++)
			kval = (kval << 1) | ((cbuf[i] >> (7 - j)) & 1);
	/* hex convert and truncate */
	snprintf(buf,MAX_STR,"%08x",kval);
	buf[6] = '\0';


	printf("Enter into snk:");
	printf("%3.3o %3.3o %3.3o %3.3o ",p1[0],p1[1],p1[2],p1[3]);
	printf("%3.3o %3.3o %3.3o %3.3o\n",p2[0],p2[1],p2[2],p2[3]);
	printf("Checksum: %s\n",buf);
	exit(0);
}
