72.

Learn Encryption Techniques with BASIC and C++
(Publisher: Wordware Publishing, Inc.)
Author(s): Gil Held
ISBN: 1556225989
Publication Date: 10/01/98

Previous Table of Contents Next


The RANDOM3.CPP Program

Continuing a presentation of C++ coding examples, Listing 6.18 lists the statements in the file RANDOM3.CPP. This file, along with its executable version named RANDOM3.EXE, is stored in the C directory on the companion CD-ROM.

In examining the program listing contained in Listing 6.18, note the functions encryptKeyboardText and encryptFile. The first function writes text entered via the keyboard to an input file and encrypts it to an output file. The second function, encryptFile, encrypts the contents of an input file. Two additional functions that warrant your attention include getCode and setupSeed as a pointer into the C++ random number generator. Since the executable version of RANDOM3.CPP produces similar results to the execution of RANDOM3.BAS, I will leave it to you to use the program.

Listing 6.18 The RANDOM3.CPP program listing.

 /* random3.cpp C++ code written by Jonathan Held, May 14, 1998, using Microsoft's Visual C++ version 5.0. */ //standard includes #include <iostream.h> #include <string.h> #include <stdlib.h> #include <iomanip.h> #include <fstream.h> //function prototypes void setupSeed(char *); void display(char *); void encrypt(ofstream, char []); void encryptKeyboardText(char *, char *); bool encryptFile(char *, char *); void formatData(char []); void getCode(char *&); void getFileNames(char * &, char * &); int getInputType(void); void groupBUFFER(ofstream, char [], int); //---------------------------------------------------------------- //Function: main() //Parameters: None //Return Type: int - 0 means program terminated normally, any other //value means abnormal termination //Purpose: Runs the main part of the program. //---------------------------------------------------------------- int main(){   char * the_Code, *infile, *outfile;   int input_type;   getCode(the_Code);   setupSeed(the_Code);   getFileNames(infile, outfile);   input_type = getInputType();   //do something with file input first   if (input_type){      encryptFile(infile, outfile);      cin.get();      display(outfile);   }   else {     encryptKeyboardText(infile, outfile);     display(outfile);   }   return 0; }//end main() //---------------------------------------------------------------- //Function: display() //Parameters: name - the name of the file the user wants displayed //Return Type: None //Purpose: Echoes the resulting output file to the screen. //---------------------------------------------------------------- void display(char *name) {   const int SIZE = 256;   ifstream infile(name, ios::in);   char input[SIZE];   cout << "Press return to display the encrypted file.";   cin.getline(input, SIZE, '\n');   strcpy(input, input+strlen(input));   if (!(infile)){     cerr << "Unable to open input file for display." << endl;   }   else {     while (infile.getline(input, SIZE, '\n')){      cout << input << endl;     }   }   cout << endl;   infile.close();   return; }//end display() //---------------------------------------------------------------- //Function: encrypt() //Parameters: wt - the output stream //      text - the text that needs to be encrypted //Return Type: None //Purpose: Performs the encryption of the client's text based on //random numbers. //---------------------------------------------------------------- void encrypt(ofstream wt, char text[]){   const int SIZE = 256;   char plaintext[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";   int x, ix, jx, location;   for (ix=0; ix < strlen(text); ix++){     x = (rand() % 26);   for (jx=0; jx < strlen(plaintext); jx++){     if (text[ix] == plaintext[jx])         location = jx;   }   text[ix] = plaintext[(x + location)%26];  }  groupBUFFER(wt, text, strlen(text));  return; }//end encrypt() //---------------------------------------------------------------- //Function: encryptKeyboardText //Parameters: in - the input file name //      op  - the output file name //Return Type: None //Purpose: Writes the client's text to an input file and encrypts //it to an output file. //---------------------------------------------------------------- void encryptKeyboardText(char *in, char *op){   const int SIZE = 256;   const int NEW_LINE = 92;   char buffer[SIZE];   bool go_on = true;   ofstream input(in, ios:: out);   ofstream output(op, ios::out);   if ((!input) || (!output)){      cerr << "Unable to open file " << in << " or " << op               << "." << endl;   }   else {     cout << "Enter the message in UPPERCASE or lowercase characters. "                      << endl           << "Non-alphabetic characters may be entered but are                      ignored." << endl           << "Use a / at the beginning of each line that should                      remain" << endl           << "in plaintext and a \\ on a separate line to indicate                     the" << endl           << "end of an enciphered message." << endl << endl;    while (go_on){     cin.getline(buffer, SIZE, '\n');    input << buffer << endl;    if (buffer[0] == '/'){    output << buffer << endl;  }  else if (((int) buffer[0]) == NEW_LINE){   go_on = false;  }  else {      formatData(buffer);       encrypt(output, buffer);      }   }  }  input.close();  output.close();  cout << "Plaintext saved in " << in << endl    << "Encrypted text in  " << op << endl << endl;  return; }//end encryptKeyboardText() //---------------------------------------------------------------- //Function: encryptFile() //Parameters: inp - the input file name //      op  - the output file name //Return Type: bool indicating success of the operation //Purpose: Encrypts the contents of a file. //---------------------------------------------------------------- bool encryptFile(char *inp, char *op){  const int SIZE = 256;  char buffer[256];  bool success = false;  //declare file stream objects  ifstream input(inp, ios::in);  ofstream output(op, ios::out);  if ((!input) || (!output)){          cerr << "Unable to open/write to files " << inp << " or "               << op << "." << endl;  }  else {    success = true;    while (input.getline(buffer, SIZE, '\n')){     if (buffer[0] == '/'){         output << buffer << endl;         strcpy(buffer, buffer+strlen(buffer));      }       else {        formatData(buffer);        encrypt(output, buffer);      }     }   }   input.close();   output.close();   return success; }//end encryptFile() //---------------------------------------------------------------- //Function: formatData() //Parameters: data - the array we want to format //Return Type: None //Purpose: Get rid of all spaces in the array. //---------------------------------------------------------------- void formatData(char data[]) {  for (int mx=0, nx=0; (*(data+nx) != '\0'); nx++){   if (*(data+nx) == ' '){      //do nothing - skip over the space in the data   }   else {     *(data+mx++) = *(data+nx);   }  }  //don't forget to add the null terminator  *(data+mx) = '\0';  return; }//end formatData() //---------------------------------------------------------------- //Function: getCode() //Parameters: the_Code - the code that will be entered by the client //Return Type: None //Purpose: Prompts the client for a keyword of at least six characters. //Checks the length of the keyword entered to make sure it has the //required number of characters.  If it doesn't, it prints an error //message and prompts for a keyword again. //---------------------------------------------------------------- void getCode(char *&the_Code){  int length;  bool go_on = true;  char buffer[1000];  while(go_on){   cout << "Enter your secret code (6 characters minimum): ";   cin >> buffer;   length = strlen(buffer);   if (length < 6) {   cerr << "\aCode must be 6 characters or more!"       << endl << endl;   }   else {    the_Code = new char[length];    strcpy(the_Code, buffer);    go_on = false;   }  }  return; }//end getCode() //---------------------------------------------------------------- //Function: getFileNames() //Parameters:  infile_name - the input file //      outfile_name - the output file we will write the //      enciphered text to //Return Type: None //Purpose: Get file information from the user. //---------------------------------------------------------------- void getFileNames(char * &infile_name, char * &outfile_name) {   const int SIZE = 256;   char data[SIZE];   cout << "Enter filename to store/retrieve plaintext message: ";   cin >> data;   infile_name = new char[strlen(data) + 1];   strcpy(infile_name, data);   cout << "Enter filename to store enciphered message: ";   cin >> data;   outfile_name = new char[strlen(data) + 1];   strcpy(outfile_name, data);   return; }//end getFileNames() //---------------------------------------------------------------- //Function: getInputType() //Parameters: None //Return Type: int - 0 indicates keyboard input, 1 indicates file //       input //Purpose: Determines if the user will be manually entering text to //be enciphered or if the user wants a file to be enciphered. //---------------------------------------------------------------- int getInputType(void) {   char type;   bool error = false;   int value;   do {     //prompt user for input from file or keyboard     cout << "Is file input from keyboard (K, k) or file (F, f): ";     cin >> type;     //make type an uppercase letter     type =static_cast<char>(toupper(static_cast<int>(type)));      //check for an invalid character      if ((type != 'K') && (type != 'F')){        cerr << "You have entered an invalid character!" << endl << endl;        error = true;      }      else {        if (type == 'K')           value = 0;        //value of 0 represents keyboard input           else value = 1;   //value of 1 represents file input        error = false;     }   } while (error);   cout << endl;   return value; }//end getInputType() //---------------------------------------------------------------- //Function: groupBUFFER() //Parameters: out - the output stream we are writing to //      num - the number of characters we want to output //      buffer - the buffer to be written to the stream //Return Type: None //Purpose: Output the buffer in groups of five characters at a //time. //---------------------------------------------------------------- void groupBUFFER(ofstream out, char buffer[], int num) {   for (int kx=0;kx<num;kx++){    if ((kx!=0) && (kx%25==0)){       out << endl;    }    if ((kx!=0) && (kx%5 == 0) && (kx%25!=0)){       out << " " << *(buffer+kx);    }    else {       out << *(buffer+kx);   } }  out << endl;  return; }//end groupBUFFER() //---------------------------------------------------------------- //Function: setupSeed() //Parameters: the_Code - a pointer to the keyword entered by the //client //Return Type: None //Purpose: Sets up the random number seed based on the keyword //code entered by the client. //---------------------------------------------------------------- void setupSeed(char *the_Code){  int seed = (int)*the_Code * (int)(*(the_Code+1));  int max = (int)(*(the_Code+2)) * (int)(*(the_Code+3));  float dummy;  int increment;  srand(seed);  increment = (int) (*(the_Code + 4));  for (int ix=1; ix<max; ix+=increment)    dummy = ((float) rand() )/RAND_MAX;  max = (int)(*(the_Code + 4)) * (int) (*(the_Code+5));  for (int jx=1; jx<max; jx+=increment)   dummy = ((float) rand() )/RAND_MAX;  return; }//end setupSeed() //end file random3.cpp 


Previous Table of Contents Next


Learn Encryption Techniques with Basic and C++
Learn Encryption Techniques with BASIC and C++
ISBN: 1556225989
EAN: 2147483647
Year: 2005
Pages: 92
Authors: Gil Held

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net