hey can anyone help me with the decrypt part...cant seem to get it to work....

#include <iostream>
using namespace std;

unsigned char s[256];
unsigned int i, j;

void swap(unsigned char *s, unsigned int i, unsigned int j)
{
   unsigned char temp = s[i];
   s[i] = s[j];
   s[j] = temp;
}

void rc4_KSA (const char *key, unsigned int keylen)
{
    int a=0, b=0;
    for (a = 0; a < 256; a++)
    {
        s[a] = a;
    }

    for (a = 0, b = 0; a < 256; a++)
    {
        b = (b + key[a % keylen ] + s[a]) % 256;
        swap(s, a , b);
    }
}

unsigned char rc4_PRGA()
{
    i = (i + 1) % 256;
    j = (j + s[i]) % 256;
    swap(s, i, j);
    return s[(s[i] + s[j]) % 256];
}

int main()
{
    string input;
    string plainText;
    do {
        cout << "Please enter a 16 character key (signifying 16 bytes):";
        getline(cin, input);
        if (input.length() > 16)
        {
            cout << "Entered key is more than 16 characters." <<endl;
        }
        else
        {
            break;
        }
    } while (true);

    const char* key = input.c_str();

    //create the keystream
    rc4_KSA(key, strlen(key));
    cout << "Generated Key stream:" << endl;
    for (int t = 0; t < 256; t++)
    {
        cout << s[t];
    }
    cout << endl;

    //plaintext is taken from user.
    cout << "Enter plain text (upto 1024 characters long):";
    getline(cin, plainText);

    int size = plainText.length();
    //allocate new memory blocks to hold the data
    const char* memblock = plainText.c_str();
    char* enblock = new char [size];

    //encrypt 
    for (int x = 0; x < size; x++)
    {
        enblock[x] = (memblock[x] ^ rc4_PRGA());
    }

    cout << "Generated Encrypted stream:" << endl;
    for (int y = 0; y < size; y++)
    {
        cout << enblock[y];
    }
    cout << endl;
    system("pause");

    //reset keyStream (s array)
    rc4_KSA(key,strlen(key));

    //decrypt
    for (int x = 0; x < size; x++)
    {
        enblock[x] = (enblock[x] ^ rc4_PRGA());
    }

    //print out the plaintext
    for (int x = 0; x < size; x++)
    {
        cout << enblock[x];
    }


    delete[] memblock;
    delete[] enblock;
    return 0;
}

thanks

hey can anyone help me with the decrypt part...cant seem to get it to work....

Since you didn't bother to give us any information at all, all "I can say is figure out why it doesn't work and fix it..."

Give us some details on what it does wrong and we might be able to give you a useful answer.

Edited 4 Years Ago by WaltP

This article has been dead for over six months. Start a new discussion instead.