[C++] RC4 Cipher code example

Questions about programming languages and debugging
Post Reply
User avatar
Gogeta70
^_^
^_^
Posts: 3275
Joined: 25 Jun 2005, 16:00
18

[C++] RC4 Cipher code example

Post by Gogeta70 »

This is the RC4 cipher. You may have heard of it, it's been used for things like SSL and WEP wifi security, etc. Anyway, it's extremely simple to implement in comparison to a lot of other encryption algorithms.

The following code will generate a keystream and a cipher based on user input.

Code: Select all


#include <cstdlib>
#include <cstdio>

bool run = false;
unsigned char S[256];
unsigned char swap = 0;
unsigned long i = 0, j = 0;
char key[1024] = {0};
char pt[1024] = {0};
int keylength = 0;

void KSA()
{
	for(i = 0; i < 256; i++)
	{
		S[i] = i;
	}
	
	j = 0;
	for(i = 0; i < 256; i++)
	{
		j = (j + S[i] + key[i%keylength]) % 256;
		swap = S[i];
		S[i] = S[j];
		S[j] = swap;
	}
}

unsigned char* Keystream(unsigned long rounds)
{
	unsigned char* output = new unsigned char[rounds+1];
	for(i = 0; i < rounds+1; i++)
		output[i] = 0;
	
	i = 0;
	j = 0;
	
	for(unsigned long a = 0; a < rounds; a++)
	{
		i = (i + 1) % 256;
		j = (j + S[i]) % 256;
		swap = S[i];
		S[i] = S[j];
		S[j] = swap;
		
		output[a] = S[(S[i] + S[j]) % 256];
	}
	
	return output;
}

int strlen(char* str)
{
	int counter = 0;
	for(int i = 0;; i++)
	{
		if(str[i] == 0)
			break;
		
		counter++;
	}
	
	return counter;
}

int main()
{
	
	while(1)
	{
		
		printf("Type a key to use for the RC4 algorithm: ");
		gets(key);
		keylength = strlen(key);
		printf("Type a sentence you would like to cipher: ");
		gets(pt);
		
		KSA();
		unsigned char* kstream = Keystream(64);
		printf("Keystream: %s - ", key);
		
		for(int a = 0; a < 16; a++)
		{
			printf("%.2x", kstream[a]);
		}
		printf("\n");
		
		printf("Ciphertext: %s - ", pt);
		for(int a = 0; a < strlen(pt); a++)
		{
			printf("%.2X", pt[a] ^ kstream[a]);
		}
		printf("\n\n");
		
		delete[] kstream;
		
	}
	
	return 0;
}

Wikipedia provides some test ciphers to see if the algorithm is working properly too ^_^
http://en.wikipedia.org/wiki/RC4#The_ke ... _.28KSA.29" onclick="window.open(this.href);return false;
¯\_(ツ)_/¯ It works on my machine...

User avatar
bad_brain
Site Owner
Site Owner
Posts: 11636
Joined: 06 Apr 2005, 16:00
19
Location: In your eye floaters.
Contact:

Re: [C++] RC4 Cipher code example

Post by bad_brain »

well done buddy.....I would have to google for "hello world c++" so I am always impressed when people write such code... :D
Image

Post Reply