Darshan Nayak

Full Stack Developer

Implementation of RC4 Unicast Protocol

Languages/Libraries: C#

Two-phase project for CS 890BN (Cryptography and Data Security) at University of Regina. Phase one implemented a Pseudo-Random Generation Algorithm (PRGA) for RC4 stream cipher to verify that any RC4 state can go forward and backward by using PRGA and Inverse-PRGA, respectively. Phase two implemented an RC4 state based secure unicast protocol between a 'Sender' and a 'Receiver' application with complete error-detection and error-recovery.

1) Form1.cs

Following code snippet shows how the plaintext data and its hash are encrypted.

						
//FUNCTION SNIPPET; NOT THE WHOLE CODE OF THE FUNCTION					
private void btnEncrypt_Click(object sender, EventArgs e)	//encrytps plaintext using RC4 to form ciphertext
{
	#region PRGA
	txtEventLog.Text = Ops.appendToTextbox("PRGA Begins", txtEventLog.Text);
	int i = 0, j = 0, tee = 0, kay = 0;
	int runlen = 0;//improvised a new variable which is equal to the number of bytes processed

	for (packets = 0; packets < segmentsOfPlaintext; packets++)
	{
		for (int byteInPacket = 0; byteInPacket < 252; byteInPacket++)//this loop handles encryption of plaintextPacketStream.Data
		{
			i = ((i + 1) % 256);
			j = ((j + s[i]) % 256);
			s = Ops.swapArrayElements(s, i, j);
			tee = ((s[i] + s[j]) % 256);
			kay = s[tee];//at this point, we have the byte(kay) to be XORed ready.
			plaintextPacketStream[packets].Data[byteInPacket] = (byte)(plaintextPacketStream[packets].Data[byteInPacket] ^ kay);
		}
		for (int byteInPacket = 0; byteInPacket < 16; byteInPacket++)//this loop handles encryption of plaintextPacketStream.Hash
		{
			i = ((i + 1) % 256);
			j = ((j + s[i]) % 256);
			s = Ops.swapArrayElements(s, i, j);
			tee = ((s[i] + s[j]) % 256);
			kay = s[tee];//at this point, we have the byte(kay) to be XORed ready.
			plaintextPacketStream[packets].Hash[byteInPacket] = (byte)(plaintextPacketStream[packets].Hash[byteInPacket] ^ kay);
		}
	}

	modifiedOrderOfPackets = plaintextPacketStream;
	txtEventLog.Text = Ops.appendToTextbox("Ciphertext Generation Complete", txtEventLog.Text);
	txtEventLog.Text = Ops.appendToTextbox("PRGA Ends", txtEventLog.Text);
	#endregion
}
						
                  

2) Ops2.cs

Following functions show the PRGA and IPRGA implementations.

						
public static byte[] PRGA(byte[] s,int i,int j,out int outi,out int outj)//PRGA implementation
{
	i = ((i + 1) % 256);
	j = ((j + s[i]) % 256);
	s = Ops.swapArrayElements(s, i, j);
	outi = i;
	outj = j;
	return s;
}
public static byte[] IPRGA(byte[] s, int i, int j, out int outi, out int outj)//IPRGA implementation
{
	s = Ops.swapArrayElements(s, i, j);
	j = (j - s[i] + 256) % 256;
	i = (i - 1 + 256) % 256;//this line modified; added +256 to i=(i-1)%256
	outi = i;
	outj = j;
	return s;
}