/* giusto per crittare in DES */
#define	BLOCKSIZE	1024
#define SBLOCKSIZE	8
#define MIN(a,b) ((a)<(b)?(a):(b))
#define D_NOBLK(o)      ((o)/BLOCKSIZE+(o%BLOCKSIZE?1:0))

#include "kdes.h"

void _mkencrypt(char *block,int nb,des_key_schedule *ks)
{
	unsigned long * xi;
	int i;
	char *tmp;

	xi=(long *)block;
	tmp=block;
	des_ecb_encrypt((des_cblock *)tmp,(des_cblock *)tmp,*ks,DES_ENCRYPT);
	tmp+=8;
	for (i=1;i<nb/8;i++) {
		*(xi+2)^=*xi;
		*(xi+3)^=*(xi+1);
		des_ecb_encrypt((des_cblock *)tmp,(des_cblock *)tmp,*ks,DES_ENCRYPT);
		tmp+=8;
		xi+=2;
	}
}

void _mkdecrypt(char *block,int nb,des_key_schedule *ks)
{
	unsigned long * xi,xo[2],xa[2];
	int i;
	char *tmp;

	xi=(long *)block;
	tmp=block;
	xo[0]=*xi; xo[1]=*(xi+1);
	if ((xo[0]|xo[1])!=0L)
		des_ecb_encrypt((des_cblock *)tmp,(des_cblock *)tmp,*ks,DES_DECRYPT);
	tmp+=8;
	xi=(long *)tmp;
	for (i=1;i<nb/8;i++) {
		xa[0]=*xi; xa[1]=*(xi+1);
		if ((xa[0]|xa[1])!=0L) 
			des_ecb_encrypt((des_cblock *)tmp,(des_cblock *)tmp,*ks,DES_DECRYPT);
		*(xi)^=xo[0];
		*(xi+1)^=xo[1];
		xo[0]=xa[0];  
		xo[1]=xa[1];
		tmp+=8;
		xi+=2;
	}
}

void  mkencrypt(char *block,int nb,des_key_schedule *ks)
{
	int i,r;
	char *tmp;
	
	tmp=block;
	r=nb;
	for(i=0;i<D_NOBLK(nb)&&r>0;i++)
	{
		_mkencrypt(tmp,MIN(BLOCKSIZE,r),ks);
		tmp+=BLOCKSIZE;
		r-=BLOCKSIZE;
	}
}

void  mkdecrypt(char *block,int nb,des_key_schedule *ks)
{
	int i,r;
	char *tmp;
	
	tmp=block;
	r=nb;
	for(i=0;i<D_NOBLK(nb)&&r>0;i++)
	{
		_mkdecrypt(tmp,MIN(BLOCKSIZE,r),ks);
		tmp+=BLOCKSIZE;
		r-=BLOCKSIZE;
	}
}
		
