//----------------------------------------------------------------------
// Filename:    pkcscryp.c
// Description: This file contains cryptoki crypto routines
//                              This file is machine-independent.
//
// Notice:              Copyright 1998 IBM Inc. All rights reserved.
//----------------------------------------------------------------------
//----------------------------------------
// includes
//----------------------------------------

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <io.h>
#include <process.h>
#include <time.h>

#include "pkcsjnh.h"
#include "pkcsint.h"

#define	 MID_UINT	128

// 
// Crypt data routine
//
void PKCS_crypt_data(CK_CHAR_PTR data, CK_ULONG data_len) {
	int						crypt_table[] = CRYPT_KEY;
	CK_CHAR_PTR				pdata;
	unsigned int			i;

	DEBUG_MSG("In PKCS_crypt_data\n");
	
	pdata = (CK_CHAR_PTR) malloc(data_len);
	for (i=0; i<data_len; i++) {
		if ((unsigned int)data[i] >= MID_UINT) {
			pdata[i] = (unsigned int) data[i] - MID_UINT;
		} else {
			pdata[i] = (unsigned int) data[i] + MID_UINT;
		}
	}

	memcpy(data, pdata, data_len);
	free(pdata);

	DEBUG_MSG("Exit PKCS_crypt_data\n");
}


// 
// Crypt data routine
//
void PKCS_decrypt_data(CK_CHAR_PTR data, CK_ULONG data_len) {
	int					decrypt_table[] = DECRYPT_KEY;
	CK_CHAR_PTR				pdata;
	unsigned int			i;

	DEBUG_MSG("In PKCS_decrypt_data\n");

	pdata = (CK_CHAR_PTR) malloc(data_len);
	for (i=0; i<data_len; i++) {
		if ((unsigned int)data[i] >= MID_UINT) {
			pdata[i] = (unsigned int) data[i] - MID_UINT;
		} else {
			pdata[i] = (unsigned int) data[i] + MID_UINT;
		}
	}

	memcpy(data, pdata, data_len);
	free(pdata);

	DEBUG_MSG("Exit PKCS_decrypt_data\n");
}


// 
// General serial number routine
//
void PKCS_generate_serial_number(CK_CHAR_PTR psn, CK_ULONG sn_len) {
	CK_ULONG i, d;
	
	srand(clock());
	for (i=0; i<sn_len; i++) {
		d = rand() % 10;
		_itoa(d, (char *)&psn[i], 10);
	}
}

#ifdef RSACRYPTO
	#include "rsacrypt.c"
#elif CDSACRYPTO
	#include "cdsacryp.c"
#endif