#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <limits.h>
#include <openssl/des.h>
#include <openssl/bn.h>

#define KSTYPE DES_key_schedule

/* Default is OpenBSD */
//#define LINUX

#ifdef LINUX
#define DES_ecb_encrypt des_ecb_encrypt
#define DES_key_schedule des_key_schedule
#define DES_cblock des_cblock
#define DES_set_odd_parity des_set_odd_parity
#define DES_set_key_checked des_set_key_checked
#define const_DES_cblock const_des_cblock
#define KSTYPE struct des_ks_struct
#endif

/* Default example */
/* P1 B1D7E8D70391752E35E031FC026B2FA5993EEB81CE44B2B9E7AD24E4CA9516F7 */
/* Q1 AF68C9170770BB68AA6533E0FB2B958AAB746ED09CEE1B251CB1DAD54A6E0FD8 */
/* PK BCC666083E242CD4F038528C3900D5 */

#define HEX 16
#define ENCRYPT 1
#define DECRYPT 0
#define ZEROBYTEPOS 0
#define PKLEN 30
#define PKBITS 120
#define DIVISOR 3
#define CHECKS 10

#define AUP "Usage: pkexp PARITYKEY_30_HEX_DIGITS\n2004.01.08, pmsac@toxyn.org\n"

int main(int argc, char *argv[]) {
KSTYPE ks;
unsigned char hexbyte[3];
unsigned char pk[15];
unsigned char key0[8];
unsigned char blk0[8];
unsigned char deskey[8];
unsigned char p1[32];
unsigned char q1[32];
unsigned int addp1;
unsigned int addq1;
BIGNUM *bnp1;
BIGNUM *bnq1;
BIGNUM *pkr;
char *pkrh;

int i, j;
int random = 0;

unsigned char PK[31] = "BCC666083E242CD4F038528C3900D5";

	if (argc < 2) {
		printf(AUP);
		random = 1;
	}
	if (argc >= 2) {
		if (strlen(argv[1]) != PKLEN) {
			printf(AUP);
			random = 1;
		}
		else {
			for (i = 0; i < PKLEN; i++) {
				PK[i] = argv[1][i];
				random += (PK[i] - 0x30);
			}
			PK[30] = '\0';
		}
	}

	/* Create BNs */
	if ((bnp1 = BN_new()) == NULL) {
		printf("Can't get bnp1...\n");
		return -1;
	}
	if ((bnq1 = BN_new()) == NULL) {
		printf("Can't get bnq1...\n");
		return -1;
	}
	if ((pkr = BN_new()) == NULL) {
		printf("Can't get pkr...\n");
		return -1;
	}

	/* If PK is all 0's, generate good random one... */
	/* Can take a bit... */
going_random:
	if (random == 0) {
		if (!BN_pseudo_rand(pkr, PKBITS, -1, 0)) {
			printf("Can't set pkr...\n");
			return -1;
		}
		pkrh = BN_bn2hex(pkr);
		for (i = 0; i < 30; i++) PK[i] = pkrh[i];
		PK[30] = '\0';
		free(pkrh);
	}

	/* PK to pk (ascii/hex to bin) */
	for (i = 0; i < 15; i++) {
		hexbyte[0] = PK[i*2];
		hexbyte[1] = PK[i*2+1];
		hexbyte[2] = 0;
		pk[i] = strtoul(hexbyte, NULL, HEX);
	}

	/* Fill key0 and blk0 from pk */
	for (i = 0; i < 8; i++) {
		key0[i] = pk[i];
		blk0[i] = key0[i];
	}
	key0[ZEROBYTEPOS] = 0;

	DES_set_odd_parity((DES_cblock *)key0);
	if ((j = DES_set_key_checked((const_DES_cblock *)key0, &ks))) {
		printf("Invalid DES key... code %i\n", j);
		return -1;
	}

	/* Fill deskey from key0,blk0 */
	DES_ecb_encrypt((const_DES_cblock *)blk0, (const_DES_cblock *)deskey,
	 &ks, DECRYPT);
	deskey[ZEROBYTEPOS] = 0;

	DES_set_odd_parity((DES_cblock *)deskey);
	if ((j = DES_set_key_checked((const_DES_cblock *)deskey, &ks))) {
		printf("Invalid DES key... code %i\n", j);
		return -1;
	}

	/* Fill p1 with pk[4]-pk[11] four times */
	for (i = 4; i < 12; i++) p1[i-4] = pk[i];
	for (i = 0; i < 8; i++) {
		p1[i+8] = p1[i];
		p1[i+16] = p1[i];
		p1[i+24] = p1[i];
	}
	/* Fill q1 with pk[4]-pk[11] four times (use p1) */
	for (i = 0; i < 32; i++) q1[i] = p1[i];

	/* XOR p1 bytes with 0,1,2,3 */
	for (i=0; i < 4; i++) p1[i*8] ^= i;

	/* XOR q1 bytes with 4,5,6,7 */
	for (i=0; i < 4; i++) q1[i*8] ^= (i+4);

//	printf("xp1 ");
//	for (i = 0; i < 32; i++) printf("%02X", p1[i]);
//	printf("\n");
//	printf("xq1 ");
//	for (i = 0; i < 32; i++) printf("%02X", q1[i]);
//	printf("\n");


	/* Encrypt p1 and q1 buffers with deskey */
	for (i = 0; i < 4; i++) DES_ecb_encrypt((const_DES_cblock *)&p1[i*8],
 				(const_DES_cblock *)&p1[i*8], &ks, DECRYPT);
	for (i = 0; i < 4; i++) DES_ecb_encrypt((const_DES_cblock *)&q1[i*8],
				 (const_DES_cblock *)&q1[i*8], &ks, DECRYPT);

//	printf("cp1 ");
//	for (i = 0; i < 32; i++) printf("%02X", p1[i]);
//	printf("\n");
//	printf("cq1 ");
//	for (i = 0; i < 32; i++) printf("%02X", q1[i]);
//	printf("\n");

	/* Calculate addp1 and addq1 */
	addp1 = (pk[12] << 4) | (pk[13] >> 4);
	addq1 = ((pk[13] & 0x0F) << 8) | pk[14];

	/* Set BNs */
	if (BN_bin2bn(p1, 32, bnp1) == NULL) {
		printf("Can't set bnp1...\n");
		return -1;
	}
	if (BN_bin2bn(q1, 32, bnq1) == NULL) {
		printf("Can't set bnq1...\n");
		return -1;
	}

	/* Add BNs */
	if (!BN_add_word(bnp1, (BN_ULONG)addp1)) {
		printf("Can't add to bnp1...\n");
		return -1;
	}
	if (!BN_add_word(bnq1, (BN_ULONG)addq1)) {
		printf("Can't add to bnq1...\n");
		return -1;
	}
//	printf("hacp1 ");
//	for (i = 0; i < 32; i++) printf("%02X", p1[i]);
//	printf("\n");
//	printf("hacq1 ");
//	for (i = 0; i < 32; i++) printf("%02X", q1[i]);
//	printf("\n");

	/* Store BNs */
	if (!BN_bn2bin(bnp1, p1)) {
		printf("Can't store bnp1...\n");
		return -1;
	}
	if (!BN_bn2bin(bnq1, q1)) {
		printf("Can't store bnq1...\n");
		return -1;
	}

	/* Set bit 7 of first bytes */
	p1[0]|=0x80;
	q1[0]|=0x80;

	/* Set iBNs */
	if (BN_bin2bn(p1, 32, bnp1) == NULL) {
		printf("Can't set bnp1...\n");
		return -1;
	}
	if (BN_bin2bn(q1, 32, bnq1) == NULL) {
		printf("Can't set bnq1...\n");
		return -1;
	}


	/* Check that p1 and q2 are primes */
	/* and that p1%3 == 2 and q1%3 == 2 */
	if (!BN_is_prime(bnp1, CHECKS, NULL, NULL, NULL)) {
		printf("p1 is not prime...\n");
		goto going_random;
	} else {
		if (BN_mod_word(bnp1, DIVISOR) != 2) {
			printf("p1 %% 3 != 2\n");
			goto going_random;
		}
	}
	if (!BN_is_prime(bnq1, CHECKS, NULL, NULL, NULL)) {
		printf("q1 is not prime...\n");
		goto going_random;
	} else {
		if (BN_mod_word(bnq1, DIVISOR) != 2) {
			printf("q1 %% 3 != 2\n");
			goto going_random;
		}
	}


	/* Invert p1 and q1 buffers */
	for (i = 0; i < 16; i++) p1[i]^=p1[31-i]^=p1[i]^=p1[31-i];
	for (i = 0; i < 16; i++) q1[i]^=q1[31-i]^=q1[i]^=q1[31-i];

	printf("\n");
	printf("P1 ");
	for (i = 0; i < 32; i++) printf("%02X", p1[i]);
	printf("\n");
	printf("Q1 ");
	for (i = 0; i < 32; i++) printf("%02X", q1[i]);
	printf("\n");
	printf("PK %s\n\n", PK);

	printf("key0  ");
	for (i = 0; i < 8; i++) printf("%02X", key0[i]);
	printf("\n");
	printf("blk0  ");
	for (i = 0; i < 8; i++) printf("%02X", blk0[i]);
	printf("\n");
	printf("deskey ");
	for (i = 0; i < 8; i++) printf("%02X", deskey[i]);
	printf("\n");
	printf("addp1 %03X\n", addp1);
	printf("addq1 %03X\n", addq1);
	printf("\nAlways check P1,Q1,PK against Caton and Sosia before use!\n");

	return 0;
}
