Home > Net >  RC4 encryption cpp algorithm
RC4 encryption cpp algorithm

Time:11-16

I am writing a program that can encrypt files using the cipher RC4, In my file "test.txt" is a word "Plaintext", the program should encrypt and save it also in a file (for test I was using "cout")

I thing there is a problem with the last part of the code

while ( plik.read(&x,1) )
{
  i = ( i   1 ) % 256;
  j = ( j   S [ i ] ) % 256;
  swap( S [ i ], S [ j ] );
  temp = S [ ( S [ i ]   S [ j ] ) % 256 ] ^ x;
  cout << temp;
} 

There is no errors and no warnings, What should I change?

#include <algorithm>
#include <fstream>
#include <iostream>
#include <string>

using namespace std;


int main()
{
 
 unsigned char S[256];

 int i = 0;
 for ( i = 0; i < 256; i   )
   S [ i ] = i;

 string Key;
 cout << "Enter the key: ";
 cin >> Key;

int j = 0;
 for ( i = 0; i < 256; i   )
 {
   j = ( j   S [ i ]   Key.at( i % Key.length() ) ) % 256;
   swap( S [ i ], S [ j ] );
 }

 ifstream plik; 
 string path = "tekst.txt";
 plik.open( path );
 char tekst;
 plik >> tekst;

 string printFile = "Encryption_"   path;
 ofstream outfile( printFile );
 
 char x;
 j = 0;
 i = 0;
 string temp;
 while ( plik.read(&x,1) )
 {
   i = ( i   1 ) % 256;
   j = ( j   S [ i ] ) % 256;
   swap( S [ i ], S [ j ] );
   temp = S [ ( S [ i ]   S [ j ] ) % 256 ] ^ x;
   cout << temp;
 }
 
 plik.close();
 outfile.close();
 
 return 0;
}

My key is: "key" and the result should be

My bad result

CodePudding user response:

Your algorithm is mathematically totally correct, I just did few small corrections to other parts of your code and your code made correct output.

For testing purposes lets take test examples enter image description here

  • Related