Simple command-line XOR encryptor/decryptor for files












1












$begingroup$


I just made this simple XOR encryptor and decryptor (is not yet commented).
It needs a file with the "private" key string inside.



usage:

encryptor "file to encrypt/decrypt" "file with the private key" "output file"



To decrypt, just do the same but for the inputfile, use the already encrypted file and the same file with the key.



 /*
* Encryptor
* File encryptor/decryptor.
* Works on any kind of file.
* Uses XOR encryption supplying a private key on a separate file
* that very same key file is used for both encrypt and decrypt
* example:
* create a file named key.txt and inside of it, write these characters: mZq4t7w!
* save the file and use it as a key to encrypt and decrypt any file
*
* For encryption:
* Supply the "raw" file to be encrypted, use the key file and name the output file
*
* For decryption:
* Supply the output file (encrypted), use the key file and the output file will be "raw" again.
*/
#include <cstdio>

// TODO:
// Add a command line option to display outputs
static bool consoleOutput = false;

// function that will encrypt/decrypt the file
// gets 3 args., input file, key file and output file
int Encrypt(const char* file_in, const char* keyFile_in, const char* file_out);

int main(int argc, char** argv)
{
// if there's no arguments or the user typed more than 3 arguments, tell user to use help though -h option, exit.
if( (argc == 1) || (argc > 3))
{
printf("nExecute with %s -h for more informationn", argv[0]);
return 0;
}
// if user uses help, indicate the use of the program, exit.
else if(argc == 2)
{
if((argv[1][0] == '-') && (argv[1][1] == 'h'))
{
printf("nUso: %s "in file" "file with key" "out file"n", argv[0]);
return 0;
}
}
// user typed 3 arguments, everything ok, do the magic (encryption/decryption)
Encrypt(argv[1], argv[2], argv[3]);

return 0;
}

int Encrypt(const char* file_in, const char* keyFile_in, const char* file_out)
{
//use 3 file pointers, one for input, one for key and other for output
FILE* mainFile = nullptr;
FILE* keyFile = nullptr;
FILE* outFile = nullptr;

char* inBuffer = nullptr; // buffer to store the whole file contents in memory
char key[100]; // buffer to hold the key characters found in the key file **needs some future work**
int mainFileSize = 0; // variable to hold the size of the input file size

// read input file
mainFile = fopen(file_in, "rb");

// if can't open for read, close
if(mainFile == nullptr)
{
printf("Couldn't open file %s!", file_in);
return -1;
}

// go to end of file, get the position in bytes, and store it
// the position in bytes will be the file size
fseek(mainFile, 0, SEEK_END);
mainFileSize = ftell(mainFile);
rewind(mainFile); // go to beggining of file

// if the file is 1 byte in size or is empty, exit
if(mainFileSize <= 1)
{
printf("File is empty or the file is really small (not worthy)");
return -2;
}

inBuffer = new char[mainFileSize]; // allocate memory for the file content

if(inBuffer == nullptr)
{
printf("Couldn't allocate %d bytes of memory", mainFileSize);
return -3;
}

// read the whole file on the buffer
fread(inBuffer,sizeof(char), mainFileSize, mainFile);

if(consoleOutput) //TODO: if this option is enabled, display the file contents
{
for(int i = 0; i < mainFileSize; i++)

{
putchar(inBuffer[i]);
}
puts("");
}

fclose(mainFile);

// read key file
keyFile = fopen(keyFile_in, "rb");
// if can't open for read, close
if(keyFile == nullptr)
{
printf("Couldn't open file %s!", keyFile_in);
return -1;
}

// go to end of file, get the position in bytes, and store it
// the position in bytes will be the file size
fseek(keyFile, 0, SEEK_END);
const int keyFileSize = ftell(keyFile);
rewind(keyFile); // go to beggining of file

// read the key characters on the key buffer variable
fread(key, sizeof(char), keyFileSize, keyFile);

if(consoleOutput) //TODO: if this option is enabled, display the file contents
{
for(int i = 0; i < keyFileSize; i++)
{
putchar(key[i]);
}
printf("nSize: %i", keyFileSize);
}

fclose(keyFile);

// output decryption/encryption
puts("ntStarting to do the magicn");

// do the XOR encryption
// for each character in the buffer, XOR it using the key characters
// use moddulus on the key character array using the key file size to avoid reading outside of array
// example:
// i = 20 keyFileSize = 8 (8 bytes)
// i % keyFileSize = 4
// character in the 5th position of the key array will be use to XOR the buffer character at 21th position
// write the result in the same buffer
for(int i = 0; i < mainFileSize; ++i)
{
inBuffer[i] = inBuffer[i] ^ key[i%keyFileSize];
}

if(consoleOutput) //TODO: if this option is enabled, display the file contents
{
for(int i = 0; i < mainFileSize; i++)
{
putchar(inBuffer[i]);
}
puts("");
}

// open output file for write
outFile = fopen(file_out, "wb");
// if can't open, exit
if(outFile == nullptr)
{
printf("Couldn't open file %s!", file_out);
return -1;
}

// write the whole buffer chunk in the output file
// as data was not added or removed, it is the same size as the input file
fwrite(inBuffer, sizeof(char), mainFileSize, outFile);

fclose(outFile);

// clean up the buffer
delete inBuffer;
puts("Finished!");

// bye bye!!
return 0;
}









share|improve this question









New contributor




Jonathan Michel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$








  • 1




    $begingroup$
    Welcome to Code Review! Why not comment it before asking for a review, though? Reviewers can review your use of comments, and comments will help reviewers understand your code.
    $endgroup$
    – Null
    4 hours ago










  • $begingroup$
    Hi, you're right, editing right now to include comments. Please review :)
    $endgroup$
    – Jonathan Michel
    3 hours ago
















1












$begingroup$


I just made this simple XOR encryptor and decryptor (is not yet commented).
It needs a file with the "private" key string inside.



usage:

encryptor "file to encrypt/decrypt" "file with the private key" "output file"



To decrypt, just do the same but for the inputfile, use the already encrypted file and the same file with the key.



 /*
* Encryptor
* File encryptor/decryptor.
* Works on any kind of file.
* Uses XOR encryption supplying a private key on a separate file
* that very same key file is used for both encrypt and decrypt
* example:
* create a file named key.txt and inside of it, write these characters: mZq4t7w!
* save the file and use it as a key to encrypt and decrypt any file
*
* For encryption:
* Supply the "raw" file to be encrypted, use the key file and name the output file
*
* For decryption:
* Supply the output file (encrypted), use the key file and the output file will be "raw" again.
*/
#include <cstdio>

// TODO:
// Add a command line option to display outputs
static bool consoleOutput = false;

// function that will encrypt/decrypt the file
// gets 3 args., input file, key file and output file
int Encrypt(const char* file_in, const char* keyFile_in, const char* file_out);

int main(int argc, char** argv)
{
// if there's no arguments or the user typed more than 3 arguments, tell user to use help though -h option, exit.
if( (argc == 1) || (argc > 3))
{
printf("nExecute with %s -h for more informationn", argv[0]);
return 0;
}
// if user uses help, indicate the use of the program, exit.
else if(argc == 2)
{
if((argv[1][0] == '-') && (argv[1][1] == 'h'))
{
printf("nUso: %s "in file" "file with key" "out file"n", argv[0]);
return 0;
}
}
// user typed 3 arguments, everything ok, do the magic (encryption/decryption)
Encrypt(argv[1], argv[2], argv[3]);

return 0;
}

int Encrypt(const char* file_in, const char* keyFile_in, const char* file_out)
{
//use 3 file pointers, one for input, one for key and other for output
FILE* mainFile = nullptr;
FILE* keyFile = nullptr;
FILE* outFile = nullptr;

char* inBuffer = nullptr; // buffer to store the whole file contents in memory
char key[100]; // buffer to hold the key characters found in the key file **needs some future work**
int mainFileSize = 0; // variable to hold the size of the input file size

// read input file
mainFile = fopen(file_in, "rb");

// if can't open for read, close
if(mainFile == nullptr)
{
printf("Couldn't open file %s!", file_in);
return -1;
}

// go to end of file, get the position in bytes, and store it
// the position in bytes will be the file size
fseek(mainFile, 0, SEEK_END);
mainFileSize = ftell(mainFile);
rewind(mainFile); // go to beggining of file

// if the file is 1 byte in size or is empty, exit
if(mainFileSize <= 1)
{
printf("File is empty or the file is really small (not worthy)");
return -2;
}

inBuffer = new char[mainFileSize]; // allocate memory for the file content

if(inBuffer == nullptr)
{
printf("Couldn't allocate %d bytes of memory", mainFileSize);
return -3;
}

// read the whole file on the buffer
fread(inBuffer,sizeof(char), mainFileSize, mainFile);

if(consoleOutput) //TODO: if this option is enabled, display the file contents
{
for(int i = 0; i < mainFileSize; i++)

{
putchar(inBuffer[i]);
}
puts("");
}

fclose(mainFile);

// read key file
keyFile = fopen(keyFile_in, "rb");
// if can't open for read, close
if(keyFile == nullptr)
{
printf("Couldn't open file %s!", keyFile_in);
return -1;
}

// go to end of file, get the position in bytes, and store it
// the position in bytes will be the file size
fseek(keyFile, 0, SEEK_END);
const int keyFileSize = ftell(keyFile);
rewind(keyFile); // go to beggining of file

// read the key characters on the key buffer variable
fread(key, sizeof(char), keyFileSize, keyFile);

if(consoleOutput) //TODO: if this option is enabled, display the file contents
{
for(int i = 0; i < keyFileSize; i++)
{
putchar(key[i]);
}
printf("nSize: %i", keyFileSize);
}

fclose(keyFile);

// output decryption/encryption
puts("ntStarting to do the magicn");

// do the XOR encryption
// for each character in the buffer, XOR it using the key characters
// use moddulus on the key character array using the key file size to avoid reading outside of array
// example:
// i = 20 keyFileSize = 8 (8 bytes)
// i % keyFileSize = 4
// character in the 5th position of the key array will be use to XOR the buffer character at 21th position
// write the result in the same buffer
for(int i = 0; i < mainFileSize; ++i)
{
inBuffer[i] = inBuffer[i] ^ key[i%keyFileSize];
}

if(consoleOutput) //TODO: if this option is enabled, display the file contents
{
for(int i = 0; i < mainFileSize; i++)
{
putchar(inBuffer[i]);
}
puts("");
}

// open output file for write
outFile = fopen(file_out, "wb");
// if can't open, exit
if(outFile == nullptr)
{
printf("Couldn't open file %s!", file_out);
return -1;
}

// write the whole buffer chunk in the output file
// as data was not added or removed, it is the same size as the input file
fwrite(inBuffer, sizeof(char), mainFileSize, outFile);

fclose(outFile);

// clean up the buffer
delete inBuffer;
puts("Finished!");

// bye bye!!
return 0;
}









share|improve this question









New contributor




Jonathan Michel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$








  • 1




    $begingroup$
    Welcome to Code Review! Why not comment it before asking for a review, though? Reviewers can review your use of comments, and comments will help reviewers understand your code.
    $endgroup$
    – Null
    4 hours ago










  • $begingroup$
    Hi, you're right, editing right now to include comments. Please review :)
    $endgroup$
    – Jonathan Michel
    3 hours ago














1












1








1





$begingroup$


I just made this simple XOR encryptor and decryptor (is not yet commented).
It needs a file with the "private" key string inside.



usage:

encryptor "file to encrypt/decrypt" "file with the private key" "output file"



To decrypt, just do the same but for the inputfile, use the already encrypted file and the same file with the key.



 /*
* Encryptor
* File encryptor/decryptor.
* Works on any kind of file.
* Uses XOR encryption supplying a private key on a separate file
* that very same key file is used for both encrypt and decrypt
* example:
* create a file named key.txt and inside of it, write these characters: mZq4t7w!
* save the file and use it as a key to encrypt and decrypt any file
*
* For encryption:
* Supply the "raw" file to be encrypted, use the key file and name the output file
*
* For decryption:
* Supply the output file (encrypted), use the key file and the output file will be "raw" again.
*/
#include <cstdio>

// TODO:
// Add a command line option to display outputs
static bool consoleOutput = false;

// function that will encrypt/decrypt the file
// gets 3 args., input file, key file and output file
int Encrypt(const char* file_in, const char* keyFile_in, const char* file_out);

int main(int argc, char** argv)
{
// if there's no arguments or the user typed more than 3 arguments, tell user to use help though -h option, exit.
if( (argc == 1) || (argc > 3))
{
printf("nExecute with %s -h for more informationn", argv[0]);
return 0;
}
// if user uses help, indicate the use of the program, exit.
else if(argc == 2)
{
if((argv[1][0] == '-') && (argv[1][1] == 'h'))
{
printf("nUso: %s "in file" "file with key" "out file"n", argv[0]);
return 0;
}
}
// user typed 3 arguments, everything ok, do the magic (encryption/decryption)
Encrypt(argv[1], argv[2], argv[3]);

return 0;
}

int Encrypt(const char* file_in, const char* keyFile_in, const char* file_out)
{
//use 3 file pointers, one for input, one for key and other for output
FILE* mainFile = nullptr;
FILE* keyFile = nullptr;
FILE* outFile = nullptr;

char* inBuffer = nullptr; // buffer to store the whole file contents in memory
char key[100]; // buffer to hold the key characters found in the key file **needs some future work**
int mainFileSize = 0; // variable to hold the size of the input file size

// read input file
mainFile = fopen(file_in, "rb");

// if can't open for read, close
if(mainFile == nullptr)
{
printf("Couldn't open file %s!", file_in);
return -1;
}

// go to end of file, get the position in bytes, and store it
// the position in bytes will be the file size
fseek(mainFile, 0, SEEK_END);
mainFileSize = ftell(mainFile);
rewind(mainFile); // go to beggining of file

// if the file is 1 byte in size or is empty, exit
if(mainFileSize <= 1)
{
printf("File is empty or the file is really small (not worthy)");
return -2;
}

inBuffer = new char[mainFileSize]; // allocate memory for the file content

if(inBuffer == nullptr)
{
printf("Couldn't allocate %d bytes of memory", mainFileSize);
return -3;
}

// read the whole file on the buffer
fread(inBuffer,sizeof(char), mainFileSize, mainFile);

if(consoleOutput) //TODO: if this option is enabled, display the file contents
{
for(int i = 0; i < mainFileSize; i++)

{
putchar(inBuffer[i]);
}
puts("");
}

fclose(mainFile);

// read key file
keyFile = fopen(keyFile_in, "rb");
// if can't open for read, close
if(keyFile == nullptr)
{
printf("Couldn't open file %s!", keyFile_in);
return -1;
}

// go to end of file, get the position in bytes, and store it
// the position in bytes will be the file size
fseek(keyFile, 0, SEEK_END);
const int keyFileSize = ftell(keyFile);
rewind(keyFile); // go to beggining of file

// read the key characters on the key buffer variable
fread(key, sizeof(char), keyFileSize, keyFile);

if(consoleOutput) //TODO: if this option is enabled, display the file contents
{
for(int i = 0; i < keyFileSize; i++)
{
putchar(key[i]);
}
printf("nSize: %i", keyFileSize);
}

fclose(keyFile);

// output decryption/encryption
puts("ntStarting to do the magicn");

// do the XOR encryption
// for each character in the buffer, XOR it using the key characters
// use moddulus on the key character array using the key file size to avoid reading outside of array
// example:
// i = 20 keyFileSize = 8 (8 bytes)
// i % keyFileSize = 4
// character in the 5th position of the key array will be use to XOR the buffer character at 21th position
// write the result in the same buffer
for(int i = 0; i < mainFileSize; ++i)
{
inBuffer[i] = inBuffer[i] ^ key[i%keyFileSize];
}

if(consoleOutput) //TODO: if this option is enabled, display the file contents
{
for(int i = 0; i < mainFileSize; i++)
{
putchar(inBuffer[i]);
}
puts("");
}

// open output file for write
outFile = fopen(file_out, "wb");
// if can't open, exit
if(outFile == nullptr)
{
printf("Couldn't open file %s!", file_out);
return -1;
}

// write the whole buffer chunk in the output file
// as data was not added or removed, it is the same size as the input file
fwrite(inBuffer, sizeof(char), mainFileSize, outFile);

fclose(outFile);

// clean up the buffer
delete inBuffer;
puts("Finished!");

// bye bye!!
return 0;
}









share|improve this question









New contributor




Jonathan Michel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$




I just made this simple XOR encryptor and decryptor (is not yet commented).
It needs a file with the "private" key string inside.



usage:

encryptor "file to encrypt/decrypt" "file with the private key" "output file"



To decrypt, just do the same but for the inputfile, use the already encrypted file and the same file with the key.



 /*
* Encryptor
* File encryptor/decryptor.
* Works on any kind of file.
* Uses XOR encryption supplying a private key on a separate file
* that very same key file is used for both encrypt and decrypt
* example:
* create a file named key.txt and inside of it, write these characters: mZq4t7w!
* save the file and use it as a key to encrypt and decrypt any file
*
* For encryption:
* Supply the "raw" file to be encrypted, use the key file and name the output file
*
* For decryption:
* Supply the output file (encrypted), use the key file and the output file will be "raw" again.
*/
#include <cstdio>

// TODO:
// Add a command line option to display outputs
static bool consoleOutput = false;

// function that will encrypt/decrypt the file
// gets 3 args., input file, key file and output file
int Encrypt(const char* file_in, const char* keyFile_in, const char* file_out);

int main(int argc, char** argv)
{
// if there's no arguments or the user typed more than 3 arguments, tell user to use help though -h option, exit.
if( (argc == 1) || (argc > 3))
{
printf("nExecute with %s -h for more informationn", argv[0]);
return 0;
}
// if user uses help, indicate the use of the program, exit.
else if(argc == 2)
{
if((argv[1][0] == '-') && (argv[1][1] == 'h'))
{
printf("nUso: %s "in file" "file with key" "out file"n", argv[0]);
return 0;
}
}
// user typed 3 arguments, everything ok, do the magic (encryption/decryption)
Encrypt(argv[1], argv[2], argv[3]);

return 0;
}

int Encrypt(const char* file_in, const char* keyFile_in, const char* file_out)
{
//use 3 file pointers, one for input, one for key and other for output
FILE* mainFile = nullptr;
FILE* keyFile = nullptr;
FILE* outFile = nullptr;

char* inBuffer = nullptr; // buffer to store the whole file contents in memory
char key[100]; // buffer to hold the key characters found in the key file **needs some future work**
int mainFileSize = 0; // variable to hold the size of the input file size

// read input file
mainFile = fopen(file_in, "rb");

// if can't open for read, close
if(mainFile == nullptr)
{
printf("Couldn't open file %s!", file_in);
return -1;
}

// go to end of file, get the position in bytes, and store it
// the position in bytes will be the file size
fseek(mainFile, 0, SEEK_END);
mainFileSize = ftell(mainFile);
rewind(mainFile); // go to beggining of file

// if the file is 1 byte in size or is empty, exit
if(mainFileSize <= 1)
{
printf("File is empty or the file is really small (not worthy)");
return -2;
}

inBuffer = new char[mainFileSize]; // allocate memory for the file content

if(inBuffer == nullptr)
{
printf("Couldn't allocate %d bytes of memory", mainFileSize);
return -3;
}

// read the whole file on the buffer
fread(inBuffer,sizeof(char), mainFileSize, mainFile);

if(consoleOutput) //TODO: if this option is enabled, display the file contents
{
for(int i = 0; i < mainFileSize; i++)

{
putchar(inBuffer[i]);
}
puts("");
}

fclose(mainFile);

// read key file
keyFile = fopen(keyFile_in, "rb");
// if can't open for read, close
if(keyFile == nullptr)
{
printf("Couldn't open file %s!", keyFile_in);
return -1;
}

// go to end of file, get the position in bytes, and store it
// the position in bytes will be the file size
fseek(keyFile, 0, SEEK_END);
const int keyFileSize = ftell(keyFile);
rewind(keyFile); // go to beggining of file

// read the key characters on the key buffer variable
fread(key, sizeof(char), keyFileSize, keyFile);

if(consoleOutput) //TODO: if this option is enabled, display the file contents
{
for(int i = 0; i < keyFileSize; i++)
{
putchar(key[i]);
}
printf("nSize: %i", keyFileSize);
}

fclose(keyFile);

// output decryption/encryption
puts("ntStarting to do the magicn");

// do the XOR encryption
// for each character in the buffer, XOR it using the key characters
// use moddulus on the key character array using the key file size to avoid reading outside of array
// example:
// i = 20 keyFileSize = 8 (8 bytes)
// i % keyFileSize = 4
// character in the 5th position of the key array will be use to XOR the buffer character at 21th position
// write the result in the same buffer
for(int i = 0; i < mainFileSize; ++i)
{
inBuffer[i] = inBuffer[i] ^ key[i%keyFileSize];
}

if(consoleOutput) //TODO: if this option is enabled, display the file contents
{
for(int i = 0; i < mainFileSize; i++)
{
putchar(inBuffer[i]);
}
puts("");
}

// open output file for write
outFile = fopen(file_out, "wb");
// if can't open, exit
if(outFile == nullptr)
{
printf("Couldn't open file %s!", file_out);
return -1;
}

// write the whole buffer chunk in the output file
// as data was not added or removed, it is the same size as the input file
fwrite(inBuffer, sizeof(char), mainFileSize, outFile);

fclose(outFile);

// clean up the buffer
delete inBuffer;
puts("Finished!");

// bye bye!!
return 0;
}






c++ file






share|improve this question









New contributor




Jonathan Michel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




Jonathan Michel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 3 hours ago







Jonathan Michel













New contributor




Jonathan Michel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 4 hours ago









Jonathan MichelJonathan Michel

84




84




New contributor




Jonathan Michel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Jonathan Michel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Jonathan Michel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








  • 1




    $begingroup$
    Welcome to Code Review! Why not comment it before asking for a review, though? Reviewers can review your use of comments, and comments will help reviewers understand your code.
    $endgroup$
    – Null
    4 hours ago










  • $begingroup$
    Hi, you're right, editing right now to include comments. Please review :)
    $endgroup$
    – Jonathan Michel
    3 hours ago














  • 1




    $begingroup$
    Welcome to Code Review! Why not comment it before asking for a review, though? Reviewers can review your use of comments, and comments will help reviewers understand your code.
    $endgroup$
    – Null
    4 hours ago










  • $begingroup$
    Hi, you're right, editing right now to include comments. Please review :)
    $endgroup$
    – Jonathan Michel
    3 hours ago








1




1




$begingroup$
Welcome to Code Review! Why not comment it before asking for a review, though? Reviewers can review your use of comments, and comments will help reviewers understand your code.
$endgroup$
– Null
4 hours ago




$begingroup$
Welcome to Code Review! Why not comment it before asking for a review, though? Reviewers can review your use of comments, and comments will help reviewers understand your code.
$endgroup$
– Null
4 hours ago












$begingroup$
Hi, you're right, editing right now to include comments. Please review :)
$endgroup$
– Jonathan Michel
3 hours ago




$begingroup$
Hi, you're right, editing right now to include comments. Please review :)
$endgroup$
– Jonathan Michel
3 hours ago










2 Answers
2






active

oldest

votes


















0












$begingroup$



  • Any time you feel compelled to put a comment like



        // read key file


    consider factoring the relevant code into a function, e.g. read_key_file(....). Notice how the comment becomes unnecessary.




  • If you can process a stream, do process a stream. Read stdin, output to stdout. The benefits of stream processing are




    • No need to allocate a (possibly huge) buffer for am input file


    • The program can be part of a pipeline




  • The int mainFileSize; is more than questionable. File size may well exceed the limit of int. It may even exceed the limits of long which ftell returns. Use ftello (which returns off_t, wide enough to accommodate any file size).


  • The only place you do need to know the file size, and allocate a buffer dynamically, is reading of the key file. If the key file is larger than 100 bytes, your code faces an out-of-bound access problems.


  • As a side note, I don't see a reason for consoleOutput flag to exist. There are better debugging techniques. In any case, if you want to use it, provide a command line option to control its value.







share|improve this answer









$endgroup$













  • $begingroup$
    Thank you!, I used standard input/ouput to reduce exe size :). Let me work on the streams, and use off_t instead of int. Thanks for all the feedback :)
    $endgroup$
    – Jonathan Michel
    3 hours ago












  • $begingroup$
    @JonathanMichel To avoid a confusion, I said streams meaning stdin and stdout instead of opening named files, so that the program can be called as encrypt key < infile > outfile
    $endgroup$
    – vnp
    2 hours ago



















0












$begingroup$

In general, your program is very C-like. I would raise at least the following points:




  • When writing C++, you might prefer std::cout to printf. Some points regarding this are raised for instance in this SO question.


  • In contrast to C, when writing C++, you should strive to declare variables as late as possible. This increases readability and advocates efficiency (e.g., if you exit early, was it really worth initializing all those gazillion variables?). For example, don't define keyFile and outFile at the beginning of Encrypt; it's not their place of use. As a C++ programmer, if I see something like keyFile being used, I instinctively look for its type somewhere nearby, perhaps only to discover I have to scroll up considerably before finding it making it harder to understand the code.


  • Luckily, C++ offers classes which do dynamic memory management for you. Instead of using an array of characters (like char key[100]), consider using std::string. With a character array, you have to take care in not overflowing (is 100 characters really sufficient? What happens if not?).


  • Consider avoiding manual memory management via new and delete. Mistakes are easy to make and notoriously hard to catch in larger & more complex systems. Tools like std::shared_ptr are specifically designed to help you in these cases.







share|improve this answer









$endgroup$













    Your Answer





    StackExchange.ifUsing("editor", function () {
    return StackExchange.using("mathjaxEditing", function () {
    StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
    StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
    });
    });
    }, "mathjax-editing");

    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "196"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });






    Jonathan Michel is a new contributor. Be nice, and check out our Code of Conduct.










    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f214067%2fsimple-command-line-xor-encryptor-decryptor-for-files%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0












    $begingroup$



    • Any time you feel compelled to put a comment like



          // read key file


      consider factoring the relevant code into a function, e.g. read_key_file(....). Notice how the comment becomes unnecessary.




    • If you can process a stream, do process a stream. Read stdin, output to stdout. The benefits of stream processing are




      • No need to allocate a (possibly huge) buffer for am input file


      • The program can be part of a pipeline




    • The int mainFileSize; is more than questionable. File size may well exceed the limit of int. It may even exceed the limits of long which ftell returns. Use ftello (which returns off_t, wide enough to accommodate any file size).


    • The only place you do need to know the file size, and allocate a buffer dynamically, is reading of the key file. If the key file is larger than 100 bytes, your code faces an out-of-bound access problems.


    • As a side note, I don't see a reason for consoleOutput flag to exist. There are better debugging techniques. In any case, if you want to use it, provide a command line option to control its value.







    share|improve this answer









    $endgroup$













    • $begingroup$
      Thank you!, I used standard input/ouput to reduce exe size :). Let me work on the streams, and use off_t instead of int. Thanks for all the feedback :)
      $endgroup$
      – Jonathan Michel
      3 hours ago












    • $begingroup$
      @JonathanMichel To avoid a confusion, I said streams meaning stdin and stdout instead of opening named files, so that the program can be called as encrypt key < infile > outfile
      $endgroup$
      – vnp
      2 hours ago
















    0












    $begingroup$



    • Any time you feel compelled to put a comment like



          // read key file


      consider factoring the relevant code into a function, e.g. read_key_file(....). Notice how the comment becomes unnecessary.




    • If you can process a stream, do process a stream. Read stdin, output to stdout. The benefits of stream processing are




      • No need to allocate a (possibly huge) buffer for am input file


      • The program can be part of a pipeline




    • The int mainFileSize; is more than questionable. File size may well exceed the limit of int. It may even exceed the limits of long which ftell returns. Use ftello (which returns off_t, wide enough to accommodate any file size).


    • The only place you do need to know the file size, and allocate a buffer dynamically, is reading of the key file. If the key file is larger than 100 bytes, your code faces an out-of-bound access problems.


    • As a side note, I don't see a reason for consoleOutput flag to exist. There are better debugging techniques. In any case, if you want to use it, provide a command line option to control its value.







    share|improve this answer









    $endgroup$













    • $begingroup$
      Thank you!, I used standard input/ouput to reduce exe size :). Let me work on the streams, and use off_t instead of int. Thanks for all the feedback :)
      $endgroup$
      – Jonathan Michel
      3 hours ago












    • $begingroup$
      @JonathanMichel To avoid a confusion, I said streams meaning stdin and stdout instead of opening named files, so that the program can be called as encrypt key < infile > outfile
      $endgroup$
      – vnp
      2 hours ago














    0












    0








    0





    $begingroup$



    • Any time you feel compelled to put a comment like



          // read key file


      consider factoring the relevant code into a function, e.g. read_key_file(....). Notice how the comment becomes unnecessary.




    • If you can process a stream, do process a stream. Read stdin, output to stdout. The benefits of stream processing are




      • No need to allocate a (possibly huge) buffer for am input file


      • The program can be part of a pipeline




    • The int mainFileSize; is more than questionable. File size may well exceed the limit of int. It may even exceed the limits of long which ftell returns. Use ftello (which returns off_t, wide enough to accommodate any file size).


    • The only place you do need to know the file size, and allocate a buffer dynamically, is reading of the key file. If the key file is larger than 100 bytes, your code faces an out-of-bound access problems.


    • As a side note, I don't see a reason for consoleOutput flag to exist. There are better debugging techniques. In any case, if you want to use it, provide a command line option to control its value.







    share|improve this answer









    $endgroup$





    • Any time you feel compelled to put a comment like



          // read key file


      consider factoring the relevant code into a function, e.g. read_key_file(....). Notice how the comment becomes unnecessary.




    • If you can process a stream, do process a stream. Read stdin, output to stdout. The benefits of stream processing are




      • No need to allocate a (possibly huge) buffer for am input file


      • The program can be part of a pipeline




    • The int mainFileSize; is more than questionable. File size may well exceed the limit of int. It may even exceed the limits of long which ftell returns. Use ftello (which returns off_t, wide enough to accommodate any file size).


    • The only place you do need to know the file size, and allocate a buffer dynamically, is reading of the key file. If the key file is larger than 100 bytes, your code faces an out-of-bound access problems.


    • As a side note, I don't see a reason for consoleOutput flag to exist. There are better debugging techniques. In any case, if you want to use it, provide a command line option to control its value.








    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered 3 hours ago









    vnpvnp

    39.8k232101




    39.8k232101












    • $begingroup$
      Thank you!, I used standard input/ouput to reduce exe size :). Let me work on the streams, and use off_t instead of int. Thanks for all the feedback :)
      $endgroup$
      – Jonathan Michel
      3 hours ago












    • $begingroup$
      @JonathanMichel To avoid a confusion, I said streams meaning stdin and stdout instead of opening named files, so that the program can be called as encrypt key < infile > outfile
      $endgroup$
      – vnp
      2 hours ago


















    • $begingroup$
      Thank you!, I used standard input/ouput to reduce exe size :). Let me work on the streams, and use off_t instead of int. Thanks for all the feedback :)
      $endgroup$
      – Jonathan Michel
      3 hours ago












    • $begingroup$
      @JonathanMichel To avoid a confusion, I said streams meaning stdin and stdout instead of opening named files, so that the program can be called as encrypt key < infile > outfile
      $endgroup$
      – vnp
      2 hours ago
















    $begingroup$
    Thank you!, I used standard input/ouput to reduce exe size :). Let me work on the streams, and use off_t instead of int. Thanks for all the feedback :)
    $endgroup$
    – Jonathan Michel
    3 hours ago






    $begingroup$
    Thank you!, I used standard input/ouput to reduce exe size :). Let me work on the streams, and use off_t instead of int. Thanks for all the feedback :)
    $endgroup$
    – Jonathan Michel
    3 hours ago














    $begingroup$
    @JonathanMichel To avoid a confusion, I said streams meaning stdin and stdout instead of opening named files, so that the program can be called as encrypt key < infile > outfile
    $endgroup$
    – vnp
    2 hours ago




    $begingroup$
    @JonathanMichel To avoid a confusion, I said streams meaning stdin and stdout instead of opening named files, so that the program can be called as encrypt key < infile > outfile
    $endgroup$
    – vnp
    2 hours ago













    0












    $begingroup$

    In general, your program is very C-like. I would raise at least the following points:




    • When writing C++, you might prefer std::cout to printf. Some points regarding this are raised for instance in this SO question.


    • In contrast to C, when writing C++, you should strive to declare variables as late as possible. This increases readability and advocates efficiency (e.g., if you exit early, was it really worth initializing all those gazillion variables?). For example, don't define keyFile and outFile at the beginning of Encrypt; it's not their place of use. As a C++ programmer, if I see something like keyFile being used, I instinctively look for its type somewhere nearby, perhaps only to discover I have to scroll up considerably before finding it making it harder to understand the code.


    • Luckily, C++ offers classes which do dynamic memory management for you. Instead of using an array of characters (like char key[100]), consider using std::string. With a character array, you have to take care in not overflowing (is 100 characters really sufficient? What happens if not?).


    • Consider avoiding manual memory management via new and delete. Mistakes are easy to make and notoriously hard to catch in larger & more complex systems. Tools like std::shared_ptr are specifically designed to help you in these cases.







    share|improve this answer









    $endgroup$


















      0












      $begingroup$

      In general, your program is very C-like. I would raise at least the following points:




      • When writing C++, you might prefer std::cout to printf. Some points regarding this are raised for instance in this SO question.


      • In contrast to C, when writing C++, you should strive to declare variables as late as possible. This increases readability and advocates efficiency (e.g., if you exit early, was it really worth initializing all those gazillion variables?). For example, don't define keyFile and outFile at the beginning of Encrypt; it's not their place of use. As a C++ programmer, if I see something like keyFile being used, I instinctively look for its type somewhere nearby, perhaps only to discover I have to scroll up considerably before finding it making it harder to understand the code.


      • Luckily, C++ offers classes which do dynamic memory management for you. Instead of using an array of characters (like char key[100]), consider using std::string. With a character array, you have to take care in not overflowing (is 100 characters really sufficient? What happens if not?).


      • Consider avoiding manual memory management via new and delete. Mistakes are easy to make and notoriously hard to catch in larger & more complex systems. Tools like std::shared_ptr are specifically designed to help you in these cases.







      share|improve this answer









      $endgroup$
















        0












        0








        0





        $begingroup$

        In general, your program is very C-like. I would raise at least the following points:




        • When writing C++, you might prefer std::cout to printf. Some points regarding this are raised for instance in this SO question.


        • In contrast to C, when writing C++, you should strive to declare variables as late as possible. This increases readability and advocates efficiency (e.g., if you exit early, was it really worth initializing all those gazillion variables?). For example, don't define keyFile and outFile at the beginning of Encrypt; it's not their place of use. As a C++ programmer, if I see something like keyFile being used, I instinctively look for its type somewhere nearby, perhaps only to discover I have to scroll up considerably before finding it making it harder to understand the code.


        • Luckily, C++ offers classes which do dynamic memory management for you. Instead of using an array of characters (like char key[100]), consider using std::string. With a character array, you have to take care in not overflowing (is 100 characters really sufficient? What happens if not?).


        • Consider avoiding manual memory management via new and delete. Mistakes are easy to make and notoriously hard to catch in larger & more complex systems. Tools like std::shared_ptr are specifically designed to help you in these cases.







        share|improve this answer









        $endgroup$



        In general, your program is very C-like. I would raise at least the following points:




        • When writing C++, you might prefer std::cout to printf. Some points regarding this are raised for instance in this SO question.


        • In contrast to C, when writing C++, you should strive to declare variables as late as possible. This increases readability and advocates efficiency (e.g., if you exit early, was it really worth initializing all those gazillion variables?). For example, don't define keyFile and outFile at the beginning of Encrypt; it's not their place of use. As a C++ programmer, if I see something like keyFile being used, I instinctively look for its type somewhere nearby, perhaps only to discover I have to scroll up considerably before finding it making it harder to understand the code.


        • Luckily, C++ offers classes which do dynamic memory management for you. Instead of using an array of characters (like char key[100]), consider using std::string. With a character array, you have to take care in not overflowing (is 100 characters really sufficient? What happens if not?).


        • Consider avoiding manual memory management via new and delete. Mistakes are easy to make and notoriously hard to catch in larger & more complex systems. Tools like std::shared_ptr are specifically designed to help you in these cases.








        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 3 hours ago









        JuhoJuho

        56029




        56029






















            Jonathan Michel is a new contributor. Be nice, and check out our Code of Conduct.










            draft saved

            draft discarded


















            Jonathan Michel is a new contributor. Be nice, and check out our Code of Conduct.













            Jonathan Michel is a new contributor. Be nice, and check out our Code of Conduct.












            Jonathan Michel is a new contributor. Be nice, and check out our Code of Conduct.
















            Thanks for contributing an answer to Code Review Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            Use MathJax to format equations. MathJax reference.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f214067%2fsimple-command-line-xor-encryptor-decryptor-for-files%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            How to make a Squid Proxy server?

            第一次世界大戦

            Touch on Surface Book