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;
}
http://en.wikipedia.org/wiki/RC4#The_ke ... _.28KSA.29" onclick="window.open(this.href);return false;