How to Encrypt / Decrypt a text file c++

i tried working on an application that is pretty much on the spot.

has a switch on it to choose between Encryption or decryption. Hopefully this help anyone who has this as a project of some sort. Have funn -Jurgen B



#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <cmath>
using namespace std;

int main(){

int p;
printf("Cfare veprimi deshiron te besh..? :\n");
printf("Encryption = 1\nDecryption = 2\n");
cin >> p;

switch (p) {
case 1:
FILE *fdr,*fdw;
char ch,fileName[20],output[20];
int op;
printf("Vendos emrin e File qe deshiron te besh Encrypt:\n");
scanf("%s",fileName);

printf("Ne cfare emri deshironi ta ruani filein e ri? \n:");
scanf("%s",output);

fdr=fopen(fileName,"r");
fdw=fopen(output,"w");

if(fdr==NULL){
printf("\nFile nuk ekziston...!\n");
exit(0);
}
ch=fgetc(fdr);
while(ch!=EOF){
op=(int)ch;
op=op+5;
fprintf(fdw,"%c",op);
ch=fgetc(fdr);
}
fclose(fdw);
fclose(fdr);
printf("File-i eshte encriptuar me sukses...\n",output);
return 0;
break;

case 2:
FILE *fdrr,*fdww;
char chh,fileNamee[20],outputt[20];
int opp;
printf("Vendos emrin e File qe deshiron te besh Decrypt:\n");
scanf("%s",fileNamee);

printf("Ne cfare emri deshironi ta ruani filein e ri?:\n");
scanf("%s",outputt);

fdrr=fopen(fileNamee,"r");
fdww=fopen(outputt,"w");

if(fdrr==NULL){
printf("\nFile nuk ekziston...!\n");
exit(0);
}
chh=fgetc(fdrr);
while(chh!=EOF){
opp=(int)chh;
opp=opp-5;
fprintf(fdww,"%c",opp);
chh=fgetc(fdrr);
}
fclose(fdww);
fclose(fdrr);

printf("Decryptimi i fileit eshte bere me sukses..\n",outputt);
return 0;
break;
}


return 0;
}
looks like a lot of work.

this will encrypt and decrypt the file and its more secure than you might think (its breakable, but it takes a lot of work). Its fine for casual data encryption to deter nosey people :)

int password;
cin >> password;
srand(password);

for(all the bytes)
{
byte ^= rand()%256;
write byte to encrypted file
}

If they give the wrong password, it just gives garbage output.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <fstream>
#include <cctype>
#include <iterator>
#include <algorithm>
using namespace std;

int n, CYCLE = 26;

char encode( char c )
{
   char c0 = isupper( c ) ? 'A' : 'a';
   if ( isalpha( c ) ) c = c0 + ( c - c0 + n ) % CYCLE;
   return c;
}

int main( int argc, char *argv[] )
{
   ifstream in( argv[1] );
   ofstream out( argv[2] );
   n = atoi( argv[3] ) + CYCLE;          // + CYCLE because % works inconsistently with negatives
   transform( istream_iterator<char>{in >> noskipws}, {}, ostream_iterator<char>{out}, encode );
}



Usage to encode (e.g. for 5-character Caesar shift):
encodeFile.exe infile outfile 5

Usage to decode:
encodeFile.exe outfile result -5

Hopefully infile and result are the same.


You can replace routine encode by whatever character-encoding routine you like.
Topic archived. No new replies allowed.