www.pudn.com > CipherSystem.rar > RC4CipherSystem.cpp


#include "stdafx.h" 
#include "RC4CipherSystem.h" 
 
 
 
////////////////////////////////////////////////////////////////////////////////////// 
////////////////        Implement class of RC4CipherSystem    //////////////////////// 
////////////////////////////////////////////////////////////////////////////////////// 
RC4CipherSystem::RC4CipherSystem() : iS(0), jS(0) {} 
 
void RC4CipherSystem::GetKey(int valueOfKarray[], int arrayLen) 
{ 
	SetKarray(valueOfKarray, arrayLen); 
	SetSarray(); 
	KSA(); 
 
	keyStream = ""; 
	int i; 
	for (i=0; i<(int)text.length(); i++) keyStream += PSGA(); 
	 
	return; 
} 
 
void RC4CipherSystem::GetData(const string& input) 
{ 
	text = input; 
} 
 
inline void RC4CipherSystem::SetSarray() 
{ 
	int i; 
	for (i=0; i<256; i++) S[i] = Byte(i); 
} 
 
void RC4CipherSystem::SetKarray(int array[], int arrayLen) 
{ 
	int arrayDisplace = 0; 
	int i = 0; 
	while (i < 256) K[i++] = (Byte)array[arrayDisplace++ % arrayLen]; 
 
	return; 
} 
 
void RC4CipherSystem::KSA() 
{ 
	int i, j=0; 
	for(i=0; i<256; i++) 
	{ 
		j = (j + S[i] + K[i]) % 256; 
 
		Byte t = S[i]; 
		S[i] = S[j]; 
		S[j] = t; 
	} 
} 
 
Byte RC4CipherSystem::PSGA() 
{ 
	iS = (iS + 1) % 256; 
	jS = (jS + S[iS]) % 256; 
	 
	Byte t = S[iS]; 
	S[iS] = S[jS]; 
	S[jS] = t; 
 
	t = (S[iS] + S[jS]) % 256; 
 
	return S[t]; 
} 
 
void RC4CipherSystem::Encrypt() 
{ 
	int i; 
	for (i=0; i<(int)text.length(); i++) text[i] ^= keyStream[i]; 
	string temp = text; 
	CharToBinary(temp, text); 
	for (i=0; i<(int)text.length(); i++) text[i] += 0x30; 
} 
 
void RC4CipherSystem::Decrypt() 
{ 
	int i; 
	for (i=0; i<(int)text.length(); i++) text[i] -= 0x30; 
	string temp = text; 
	BinaryToChar(temp, text); 
	for (i=0; i<(int)text.length(); i++) text[i] ^= keyStream[i]; 
}