I tried to write a simple XOR encryption program. But it's not working properly. For some files is the output file longer, for some other shorter then it should be. Here is my source code:
Code:
/*
XOR encryption - simple encryption algorithm
use: xorenc [key] filename
It encrypts file 'filename'; output is in file with the same name, but
extension is changed to .enc
*/
/*
problems:
*** should I use delete or delete[] operator?
see ~Key()
*** how to know whether it's EOF or not using cin and <iostream.h>?
see main() : while loop
*** is it good to use variable definitions in loop?
see main() : while loop
*/
#include <fstream.h>
#include <iostream.h>
#include <string.h>
#include <stdio.h>
const int MAX_KEY_LENGTH = 16;
class Key {
private:
char *key;
int next;
int length;
public:
Key(void) {
key = new char[MAX_KEY_LENGTH];
}
Key(const char *s) { init(s); }
~Key(void) { delete key; }
void init(const char *s);
char get_next_char(void);
};
void
Key::init(const char *s)
{
length = strlen(s);
if (length == 0) {
cerr << "Key is too short" << endl;
}
else if (length > MAX_KEY_LENGTH) {
length = MAX_KEY_LENGTH;
}
key = new char[length+1];
strncpy(key, s, length);
key[length] = 0;
next = 0;
}
char
Key::get_next_char(void)
{
if (next < length)
return key[next++];
// we should repeat the key from beginning
next = 1;
return key[0];
}
void
usage(const char *program)
{
cout << endl << "Use " << program << " [key] filename" << endl << endl;
}
char *
get_only_file_name(char *s)
{
int i = 0;
while (s[i] != '\0' && s[i] != '.')
i++;
if (s[i] != '\0')
s[i] = '\0';
return s;
}
char *
prompt_for_key(void)
{
char s[100];
cout << "Enter key for encrypting: ";
return fgets(s, 100, stdin); // using fgets doesn't seem good..
}
int
main(int argc, char *argv[])
{
ifstream in;
ofstream out;
Key key;
if (argc <= 1) {
cout << "Too few arguments" << endl;
usage(argv[0]);
return 0;
}
else if (argc == 2) {
in.open(argv[1]);
out.open(strcat(get_only_file_name(argv[1]), ".enc"));
key.init(prompt_for_key());
}
else if (argc >= 3) {
in.open(argv[2]);
out.open(strcat(get_only_file_name(argv[2]), ".enc"));
// creates an instance of Key class an initialize it
key.init(argv[1]);
}
if (!in)
cerr << endl << "Input file does not exist!" << endl << endl;
if (!out)
cerr << endl << "Cannot open output file!" << endl << endl;
int c;
while (1) {
in >> c;
if (in.eof())
break;
out.put(c ^ key.get_next_char());
}
in.close();
out.close();
return 0;
}
And another question is about streams. How should I test whether the file is on its end? And how about formatting the output? (in C we have %6.2f for example) Do you know about some tutorial or what, so I'd be able to read it?