#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
int encrypt(char *,char *);
int decrypt(char *,char *);
long filesize(FILE *);
int main(){
begining:
unsigned char key[128],filename[64];
textcolor(LIGHTGREEN);
cprintf("BASIC XOR ENCRYPTION BY SPADE %c") ;cout<<endl;
for(int i=0;i<80;i++)cprintf("%c",6);
cout<<endl;
cin.tie(&cout);
cout<<"Enter filename:\n";
cin>>filename;
cout<<"Enter key:\n";
cin>>key;
char op;
cout<<"Enter option<Encrypt/Decrypt>:\n";
op=getch();
switch(op){
case 'd':
case 'D':
decrypt(filename,key);
break;
case 'e':
case 'E':
encrypt(filename,key);
default:
break;
}
op=getch();
if(op==0x1b)goto end;
goto begining;
end:
return 0;
}
long filesize(FILE *stream)
{
long curpos, length;
curpos = ftell(stream);
fseek(stream, 0L, SEEK_END);
length = ftell(stream);
fseek(stream, curpos, SEEK_SET);
return length;
}
int encrypt(char *fname,char *key){
FILE *out;
unsigned char *buf;
if((out=fopen(fname,"rb+"))==NULL){textcolor(LIGHTRED);
cprintf("error opening file!!! :(");cout<<endl; return -1;}
int size=(int) filesize(out);
fseek(out, 0L, SEEK_SET);
buf=new char[size];
for(int i=0;i<size;i++){
buf[i]=fgetc(out);
}
fclose(out);
remove(fname);
if((out=fopen(fname,"ab+"))==NULL){textcolor(LIGHTRED);
cprintf("error opening file!!! :(");cout<<endl; return -1;}
for(int i=0,j=0;i<size;i++,j++){
if(j==strlen(key)-1)j=0;
buf[i]=buf[i]^key[j];
fputc(buf[i],out);
}
textcolor(YELLOW);
cprintf("File encrypted :)");cout<<endl;
return 1;
}
int decrypt(char *fname,char *key){
FILE *out;
unsigned char *buf;
if((out=fopen(fname,"rb+"))==NULL){textcolor(LIGHTRED);cprintf("error opening file!!! :(");cout<<endl; return -1;}
int size=(int) filesize(out);
fseek(out, 0L, SEEK_SET);
buf=new char[size];
for(int i=0;i<size;i++){
buf[i]=fgetc(out);
}
fclose(out);
remove(fname);
if((out=fopen(fname,"ab+"))==NULL){textcolor(LIGHTRED);
cprintf("error opening file!!! :(");
cout<<endl;
return -1;}
for(int i=0,j=0;i<size;i++,j++){
if(j==strlen(key)-1)j=0;
buf[i]=buf[i]^key[j];
fputc(buf[i],out);
}
textcolor(YELLOW);
cprintf("File decrypted :)",0x38); cout<<endl;
return 1;
}