/* This program encrypts an arbitrary data file or decrypts it. It is a very simple and easy to break encryption. A file is just a sequence of bytes and each byte is just an integer in the range 0 to 255. The key is an integer K in the same range and the encrypted form of character x is just (x + K) mod 256 (which is again in the range 0 to 255). To decrypt a character that was encrypted with key K write (x-K) mod 256. Compile as follows: % gcc encrypt.c -o encrypt See function usage() on how to use this program */ #include <stdio.h> // This function prints the syntax of the command // Pay attention to the backslashes at the end of // several lines. This is the way to write a string // constant along several lines. These backslashes // are immediately followed by a new line usage() { fprintf(stderr, "\ The usage is:\n\ encrypt (e or d) key filename\n\ where\n\ e is for encryption, d for decryption\n\ key is a number from 0 to 255\n\ filename is the name of the file to encrypt/decrypt\n"); } // This macro calls function usage and exits // We use it whenever the user did something wrong // or something went wrong. #define BAAAD {usage(); exit(1);} main(int argc, char **argv) { // this string is used my function mktemp // to create a temporary file name where // the encrypted file will be stored. // This encrypted file is then copied onto // the original file name and deleted. char tmp[]="encryptXXXXXX"; FILE *in, *out; int cin, cout; // input and output characters int key, enc; // the key and enc // enc is +1 for encryption and // -1 for decryption char command[1000]; // this is used to pass commands to // the Operating System // The number of arguments should be 4 if(argc != 4) BAAAD // First argument should be the character e or d only if((argv[1][0] != 'e') && (argv[1][0] != 'd')) BAAAD enc = (argv[1][0] == 'e')?1:(-1); // Second argument should be an integer if( 1 != sscanf(argv[2], "%d", &key)) BAAAD in = fopen(argv[3], "r"); if(!in) BAAAD // could not open file mktemp(tmp); // create a name for a temporary // file out = fopen(tmp, "w"); if(!out) BAAAD // could not open file while((cin = fgetc(in)) != EOF) { // while there are characters to read cout = (cin + enc*key) % 256; // encrypt them and write them out fputc(cout, out); } // close both files fclose(in); fclose(out); // copy temporary file onto given file sprintf(command, "cp %s %s", tmp, argv[3]); system(command); // delete temporary file sprintf(command, "rm %s", tmp); system(command); }