73.0k views
0 votes
Implement the RC4 stream cipher in C++. User should be able to enter any key that is 5 bytes to 32 bytes long. Be sure to discard the first 3072 bytes of the pseudo random numbers. THE KEY OR THE INPUT TEXT MUST NOT BE HARD CODED IN THE PROGRAM.

1 Answer

5 votes

Answer:

Step-by-step explanation:

#include <iostream>

#include <string>

#include<vector>

using namespace std;

vector<int> permute(vector<int>, vector<int>);

string encrypt(vector<int>s1 , vector<int> t1, string p);

string decrypt(vector<int>s1, vector<int> t1, string p);

int main() {

string plaintext = "cryptology";

string plaintext2 = "RC4";

vector<int> S(256);

vector<int> T(256);

int key[] = { 1,2,3,6 };

int key2[] = { 5,7,8,9 };

int tmp = 0;

for (int i = 0; i < 256;i++) {

S[i] = i;

T[i] = key[( i % (sizeof(key)/sizeof(*key)) )];

}

S = permute(S, T);

for (int i = 0; i < 256 ;i++) {

cout << S[i] << " ";

if ((i + 1) % 16 == 0)

cout << endl;

}

cout << endl;

string p = encrypt(S, T, plaintext);

cout << "Message: " << plaintext << endl;

cout << "Encrypted Message: " << " " << p << endl;

cout << "Decrypted Message: " << decrypt(S, T, p) << endl << endl;

tmp = 0;

for (int i = 0; i < 256;i++) {

S[i] = i;

T[i] = key2[(i % (sizeof(key) / sizeof(*key)))];

}

S = permute(S, T);

for (int i = 0; i < 256;i++) {

cout << S[i] << " ";

if ((i + 1) % 16 == 0)

cout << endl;

}

cout << endl;

p = encrypt(S, T, plaintext2);

cout << "Message: " << plaintext2 << endl;

cout << "Encrypted Msg: " << p << endl;

cout << "Decrypted Msg: "<<decrypt(S, T, p) << endl << endl;

return 0;

}

string decrypt(vector<int>s1, vector<int> t1, string p) {

int i = 0;

int j = 0;

int tmp = 0;

int k = 0;

int b;

int c;

int * plain = new int[p.length()];

string plainT;

for (int r = 0; r < p.length(); r++) {

i = (i + 1) % 256;

j = (j + s1[i]) % 256;

b = s1[i];

s1[i] = s1[j];

s1[j] = b;

tmp = (s1[i] + s1[j]) % 256;

k = s1[tmp];

c = ((int)p[r] ^ k);

plain[r] = c;

plainT += (char)plain[r];

}

return plainT;

}

string encrypt(vector<int>s1, vector<int> t1, string p) {

int i = 0;

int j = 0;

int tmp = 0;

int k = 0;

int b;

int c;

int * cipher = new int [p.length()];

string cipherT;

cout << "Keys Generated for plaintext: ";

for (int r = 0; r < p.length(); r++) {

i = (i + 1) % 256;

j = (j + s1[i]) % 256;

b = s1[i];

s1[i] = s1[j];

s1[j] = b;

tmp = (s1[i] + s1[j]) % 256;

k = s1[tmp];

cout << k << " ";

c = ((int)p[r] ^ k);

cipher[r] = c;

cipherT += (char)cipher[r];

}

cout << endl;

return cipherT;

}

vector<int> permute(vector<int> s1, vector<int> t1) {

int j = 0;

int tmp;

for (int i = 0; i< 256; i++) {

j = (j + s1[i] + t1[i]) % 256;

tmp = s1[i];

s1[i] = s1[j];

s1[j] = tmp;

}

return s1;

}

User Nbonniot
by
5.4k points