/*-------------------------------------------------------------------------
   RC4 stream cipher function copy right information

   Copyright (C) 2006-2008. Tang, Li <tangli@palmmicro.com>

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   This software is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
-------------------------------------------------------------------------*/

//#include "version.h"
#include "type.h"
#include "core.h"
#include "bank3.h"

UCHAR state[256];
UCHAR x, y;

void swap(PCHAR pa, PCHAR pb)
{
	UCHAR iTemp;

	iTemp = *pa;
	*pa = *pb;
	*pb = iTemp;
}

void RC4Init(PCHAR pKey, UCHAR iKeyLen)
{
	UCHAR i;

	i = 0;
	do
	{
		state[i] = i;
		i ++;
	}while (i);

	x = 0;
	do
	{
		x = x + state[i] + pKey[mod_16x8(i, iKeyLen)];
		swap(&state[i], &state[x]);
		i ++;
	}while(i);
	x = 0;
	y = 0;
}

void RC4Calc(PCHAR pDst, PCHAR pSrc, USHORT sLen)
{
	USHORT k;
	UCHAR r;

	for (k = 0; k < sLen; k ++)
	{
		x ++;
		y += state[x];
		swap(&state[x], &state[y]);
		r = state[x]+ state[y];
		*pDst++ = (*pSrc++) ^ state[r];
	}
}
