PDA

View Full Version : Simple C/C++ program



ct
22nd August 2007, 17:53
It was not long time ago that I wrote a simple C/C++ program that uses XOR encryption/decryption ( the detailed post in this topic was interesting). However, I am not so good at programming, I'm just at intermediate or may be even at beginner level. Nowe, someone quoted form seeing the following code that I don't know nothing about escaping special characters, can any one point out



#include<iostream>
#include<cstdlib>
#include<fstream>
#include<cstdio>
using namespace std;
void encryptdecrypt(string& data,string& key)
{
int keypos = 0;

for(int i = 0;i<data.length();i++)
{
data[i] = data[i] ^ key[keypos];
keypos++;
if(keypos >= key.length())
keypos = 0;
}
}
int main(int argc,char** argv)
{
string key = "";

char c;
string data = "";
if(argc == 1)
{
cout << "Usage: progname filename";
return 0;
}
cout << "Enter a password : ";
while((c = getchar()) != '\n' )
{
key += c;
}

FILE *fp;
fp = fopen(argv[1],"rb");
if(fp == NULL)
{
cout << "Sorry, File could not be opened.";
return 0;
}

while(1)
{
c = fgetc(fp);
if(feof(fp))
break;
else
data+=c;

}

encryptdecrypt(data,key);

fclose(fp);

FILE *fout;
fout = fopen(argv[1],"wb");
if(fout == NULL)
{
cout << "Sorry, File could not be opened.";
return 0;
}
for(int i = 0;i<data.length();i++)
fputc(data[i],fout);

fclose(fout);
getchar();
return 0;

}



Also, how can I improve this small program ...
Thanks.

wysota
5th September 2007, 20:37
So why don't you ask this "someone" to point the problem out for you? I don't see any special characters that need encoding here...

ct
13th September 2007, 17:22
Well, first of all it was a comment in the blog and my be insignificant. But I really want to know that I am doing things the *right* way and heading the right direction.
What do you mean by special character needing encryption ?

wysota
17th September 2007, 10:13
Not encryption. Encoding. And I don't know what the commenter meant in this particular situation. Maybe it was about escaping \0 characters so that you don't get invalid end of string prematurely. But this solely depends on how you store and use the data.

ct
25th October 2007, 14:11
Sorry, could not be in touch due to internet problem.. Aggh...that was a typo..I meant encoding all the way :D .. Thanks, yes that person might be referring to '\0'. I found a similar program in Bruce Scheigner's Applied Cryptography , in the beginning chapters..and it's short and elegent.