-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRC4.cpp
66 lines (66 loc) · 1.76 KB
/
RC4.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include<iostream>
#include<vector>
using namespace std;
class RC4{
vector<int> GenerateKey(string k, int m){
// KSA
vector<int> IVvector;
for(auto it: k){
IVvector.push_back(int(it));
}
int n = IVvector.size();
vector<int> s;
for(int i=0;i<256;i++){
s.push_back(i);
}
int j=0;
for(int i=0;i<256;i++){
j = (j+s[i]+IVvector[i%n])%256;
int temp = s[i];
s[i] = s[j];
s[j] = temp;
}
// PRGA
int i = 0;
j = 0;
vector<int> z;
while(z.size()<m){
i = (i+1)%256;
j = (j+s[i])%256;
int temp = s[i];
s[i] = s[j];
s[j] = temp;
z.push_back(s[(s[i]+s[j])%256]);
}
return z;
}
public:
string Encrypt(string message, string IV){
vector<int> Key = GenerateKey(IV, message.size());
// cout<<Key<<endl;
string Cipher = "";
vector<int> messageArray;
for(int i=0;i<message.size();i++){
Cipher.push_back(char(int(message[i])^Key[i]));
}
return Cipher;
}
string Decrypt(string Cipher, string IV){
vector<int> Key = GenerateKey(IV, Cipher.size());
// cout<<Key<<endl;
string Message = "";
vector<int> CipherArray;
for(int i=0;i<Cipher.size();i++){
Message.push_back(char(int(Cipher[i])^Key[i]));
}
return Message;
}
};
int main(){
RC4 RC;
string message = "todayismonday";
cout<<"Message : "<<message<<endl;
string cipher = RC.Encrypt(message, "10101");
cout<<"cipher : "<<cipher<<endl;
cout<<"After Decrypting : "<<RC.Decrypt(cipher, "10101");
}