45.

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 CIPHER6.CPP Program

Continuing our presentation of C++ versions of each BASIC language version, Listing 4.7 contains the program listing of CIPHER6.CPP. As you review the program listing, you will note that an extensive effort was made to make the program as “crash-free” as possible, as well as to incorporate the functionality of the BASIC language version of the program. When you examine the program listing, you may wish to focus your attention upon the functions interval, which creates the cipher stream based on interval extraction, and numericExtraction, which creates the cipher stream used to encrypt files by pulling off the columns from the matrix in alphabetical order based on the character in the top row and inserting them into the cipher array. Although many of the previously developed C++ functions are included once again in this program listing, the listing is presented in its entirety to facilitate reference to the relationship between functions as well as the manner by which they operate.

Listing 4.7 The CIPHER6.CPP program listing.

 /* cipher6.cpp C++ code written by Jonathan Held using Microsoft Visual C++, version 5.0, on March 24, 1998. */ //standard include files #include<iostream.h> #include<assert.h> #include<string.h> #include<ctype.h> #include<fstream.h> //function prototypes bool checkInput(char * &); void createCipherStream(char *, char[]); void createMatrix(char ** &, const char [], const int, const int); void display(char *); bool encryptText(char *, char *, const char [], const char[], char []); void deleteMatrix(char **&, const int, const int); int findLowestValue(int *&, const int); void formatData(char []); char* formCipheredMessage(const char[], const char [], char []); void getFileNames(char *&, char *&); int getInputType(void); int getKeyword(char *&); bool getMessage(char*, char*, char [], const char[], const char[]); void getShiftKey(char &); void groupBUFFER(ofstream, int); void interval(char[]); void numericExtraction(char **&, char [], const int, const int); void printCipherToFile(ofstream, char[]); void printMatrix(char ** &, const int, const int); void reviseCipherStream(char **&, char [], const int, const int,                            const int); void shiftKeyword(char [], const char); void simpleExtraction(char **&, char [], const int, const int); int welcome(void); //constants we will use const int ONE = 1, TWO = 2, THREE = 3, FIVE = 5, TWENTYFIVE = 25,       TWENTYSIX = 26, TWENTYSEVEN = 27, SIXTYFIVE = 65,       NINETY = 90, NINETYTWO = 92, SIZE = 256, DUMMY_VAL = 999,       BIGSIZE = 1000; char BUFFER[BIGSIZE] = {'\0'}; //---------------------------------------------------------------- //Function: main() //Parameters: None //Return Type: int - 0 execution is normal, 1 abnormal termination //Purpose: Runs the main part of the program. //---------------------------------------------------------------- int main() {  char plaintext[TWENTYSEVEN] = {'A','B','C','D','E','F','G','H',                   'I','J','K','L','M','N','O','P',                         'Q','R','S','T','U','V','W','X',                                         'Y','Z', '\0'};  char cipherStream[TWENTYSEVEN] = {'\0'};  char message_to_cipher[SIZE], enciphered_message[SIZE];  char ** cMatrix;  char *keyword, key, *infile, *outfile;  int rows, columns, input_type, encipher_type;  bool success;  encipher_type = welcome();  if(encipher_type == ONE){     getKeyword(keyword);     createCipherStream(keyword, cipherStream);     cout << "Keyword-based alphabet is: "          << cipherStream << endl << endl;     interval(cipherStream);  }  else {    //get the keyword we are going to use, determine number of rows    //and columns of our matrix    columns = getKeyword(keyword);    rows = TWENTYSIX/columns;    //integer division requires that we check and see if there is a    //remainder; if so, we need to add one extra row to our matrix    if(TWENTYSIX%columns){      rows++;    }    //create the initial ciphertext stream    createCipherStream(keyword, cipherStream);    //echo to the user what we have    cout << "Plaintext-based alphabet is: " << plaintext << endl         << "Keyword-based alphabet is:   " << cipherStream << endl                        << endl;    //insert the stream into our matrix    createMatrix(cMatrix, cipherStream, rows, columns);    reviseCipherStream(cMatrix, cipherStream, rows, columns,                    encipher_type);  }  getShiftKey(key);  shiftKeyword(cipherStream, key);  getFileNames(infile, outfile);  input_type = getInputType();  //process file input  if(input_type){    success = encryptText(infile, outfile, plaintext, cipherStream,                  enciphered_message);  }  else {    cout << "Use a \'/\' to leave a line in plaintext." << endl      << "Use a \'\\' to indicate end of message input. " << endl;    success = getMessage(infile, outfile, message_to_cipher, plaintext,     cipherStream);  }  //report success of operation  if(!success){    cerr << "Error: Invalid filename specified. Goodbye." << endl;  }  else {    cout << "Press return to display resulting enciphered message."                     << endl;    //get the newlines off the current input stream    cin.get();    if(input_type == ONE){      cin.get();    }    display(outfile);  }  //delete dynamically allocated memory accordingly  if(encipher_type != ONE)    deleteMatrix(cMatrix, rows, columns);  delete [] infile;  delete [] outfile;  delete [] keyword;  return (!success); }//end main() //---------------------------------------------------------------- //Function: checkInput() //Parameters: input - the keyword the user entered //Return Type: bool - true if the input string contains an error, //       false otherwise //Purpose: Checks the user's keyword for invalid characters. //---------------------------------------------------------------- bool checkInput(char * &input) {  bool error = false;  int count = strlen(input);  for(int ix=0; ix<count; ix++){    int char_value = static_cast<int>(*(input+ix));    //determine if the user did not enter an uppercase character    if((char_value < SIXTYFIVE) || (char_value > NINETY)){      error = true;      cerr << "You entered an invalid keyword!" << endl << endl;      break;    }  }  if(count == 0){    cerr << "You entered an invalid keyword!" << endl << endl;    error = true;  }  return error; }//end checkInput() //---------------------------------------------------------------- //Function: createCipherStream() //Parameters: input - the keyword the user entered //      cipher - the keyword alphabet that will be constructed //Return Type: None //Purpose: Creates a preliminary cipher stream that will be used to //form the cipher matrix. //---------------------------------------------------------------- void createCipherStream(char *input, char stream[]) {  bool used[TWENTYSIX];  int index = 0,    count = strlen(input);  //no characters are initially used  for(int ix=0; ix<TWENTYSIX; ix++){    used[ix] = false;  }  //keep track of each character used, start forming the keyword  //alphabet  for(int jx=0; jx<count; jx++){    //get each character of the input string (integer value)    int char_value = static_cast<int>(*(input+jx));    if(used[char_value-SIXTYFIVE]){      //do nothing - the character was already used    }    else {      //mark as used and add to the keyword alphabet      used[char_value-SIXTYFIVE] = true;      *(stream+index++) = static_cast<char>(char_value);    }  }  //go through the list of characters used - those which weren't  //used should be added to the keyword alphabet  for(int kx=0; kx<TWENTYSIX; kx++){    if(!(used[kx])){      *(stream+index++) = static_cast<char>(SIXTYFIVE+kx);    }  }  return; }//end createCipherStream() //---------------------------------------------------------------- //Function: createMatrix() //Parameters: matrix - the matrix we are going to create //      CSTREAM - the initial cipher stream based on the //          user's keyword //      ROWS - the number of rows in the matrix //      COLS - the number of columns in the matrix //Return Type: None //Purpose: Creates a numeric key transposed matrix, identical to //figure 4.4. //---------------------------------------------------------------- void createMatrix(char ** &matrix, const char CSTREAM[], const int ROWS,                     const int COLS) {  int count = 0;  //dynamically allocate memory for the RxC matrix  //we use assert to ensure that memory was allocated;  //if not, then the program will terminate abnormally   assert(matrix = new char*[ROWS]);   for(int ix=0; ix<ROWS; ix++){     *(matrix + ix) = new char[COLS];   }   //fill in the matrix   for(int jx=0; jx<ROWS; jx++){     for (int kx=0; kx<COLS; kx++){     //we only want to enter a character into the matrix     //twenty-six times - most of the time we allocate     //a matrix larger than what we will need to use; when     //we have more than 26 characters, we simply insert a     //null terminator into the matrix       if(count < TWENTYSIX)         *(*(matrix+jx)+kx) = CSTREAM[count++];             else         *(*(matrix+jx)+kx) = '\0';     }  }  return; }//end createMatrix() //---------------------------------------------------------------- //Function: encryptText() //Parameters:  inp_file - the name of the input plaintext file //       outp_file - the name of the output ciphertext file //       PTEXT[] - the plaintext alphabet //       CTEXT[] - the ciphertext alphabet //       encoded_msg[] - the message to be encoded //Return Type: bool, indicating success of operation //Purpose: Used to encrypt file input.  Takes each line of the input //file, encrypts it, and saves the result to the specified output //file. //---------------------------------------------------------------- bool encryptText(char * inp_file, char * outp_file, const char PTEXT[],           const char CTEXT[], char encoded_msg[]) {  bool success = false;  char ip[SIZE];  //declare file stream objects  ifstream input(inp_file, ios::in);  ofstream output(outp_file, ios::app);  if((!input) || (!output)){    //do nothing - I/O error; user will be notified upon    //procedure's return to main()  }  else {    success = true;    //print plaintext and ciphertext alphabets to the    //output file    output << "PLAINTEXT:  " << PTEXT << endl;    output << "CIPHERTEXT: " << CTEXT << endl << endl;    while (input.getline(ip, BIGSIZE, '\n')){    //check to see if the user wants the line to appear in plain text    if(ip[0] == '/'){      if (strlen(BUFFER)>0){          //empty whatever is in the buffer          groupBUFFER(output, strlen(BUFFER));      //adjust the buffer         strcpy(BUFFER, (BUFFER+strlen(BUFFER)));      //output plaintext      }    output << ip << endl;    }    else {      //encipher the line      char *msg = formCipheredMessage(CTEXT, ip, encoded_msg);      //print the cipher in groups of five to the ouput file      printCipherToFile(output, msg);     }    }    //empty the rest of the buffer    groupBUFFER(output, strlen(BUFFER));    //notify user where plaintext and ciphertext files are    cout << "Plaintext file is: " << inp_file << endl;    cout << "Encrypted file is: " << outp_file << endl << endl;  }  //don't forget to close the files  input.close();  output.close();  //return success of the operation  return success; }//end encryptText() //---------------------------------------------------------------- //Function: deleteMatrix() //Parameters: matrix - the matrix we are going to destroy //      R - the number of rows in the matrix //      C - the number of columns in the matrix //Return Type: None //Purpose: Destroys the dynamically allocated matrix! //---------------------------------------------------------------- void deleteMatrix(char **&matrix, const int R, const int C) {  for(int ix=0; ix<R; ix++)    delete [] *(matrix+ix);  delete [] matrix;  return; }//end deleteMatrix() //---------------------------------------------------------------- //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) {  ifstream infile(name, ios::in);  char input[SIZE];  if(!(infile)){    cerr << "Unable to open input file for display." << endl;  }  else {    while (infile.getline(input, SIZE, '\n')){     cout << input << endl;    }  }  return; }//end display() //---------------------------------------------------------------- //Function: findLowestValue() //Parameters: values - the ASCII values of all characters in the //            top row of the matrix //      COLS - the number of columns in the matrix //Return Type: int - the column we want. //Purpose: Determines what column we are going to extract from //the matrix and put into the cipher stream. //---------------------------------------------------------------- int findLowestValue(int *&values, const int COLS) {  int loc=0, lowest = DUMMY_VAL;  for(int ix = 0; ix < COLS; ix++){    if(*(values+ix) != DUMMY_VAL){      if(*(values+ix) < lowest){        lowest = *(values+ix);        loc = ix;      }    }  }  *(values+loc) = DUMMY_VAL;  return loc; }//end findLowestValue() //---------------------------------------------------------------- //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: formCipheredMessage() //Parameters:  CTEXT - the cipher alphabet we will use for substitution //      MESSAGETOCIPHER - the user's message //      enc_message - the enciphered message to be determined //Return Type: char* - a pointer to the encoded information. //Purpose: Encipher the user's message. //---------------------------------------------------------------- char* formCipheredMessage(const char CTEXT[], const char                MESSAGETOCIPHER[], char enc_message[]) {  int length = strlen(MESSAGETOCIPHER)+1;  int encode_value;  for(int ix=0; ix<length; ix++){    //test to see if we have an alphabetic character; if not,    //simply copy it to our encrypted message - this preserves    //characters such as ', ! etc...    if(!isalpha(static_cast<int>(MESSAGETOCIPHER[ix]))){      enc_message[ix] = MESSAGETOCIPHER[ix];    }    else {      //valid character - the easy way to calculate the ciphered      //character is based on the plain text's ascii character value;      //since it has to be a capital letter, it must be in the range      //from 65 to 90, with A represented by 65, Z by 90.  By simply      //subtracting 65 from the encode_value (the integer representation      //of the plaintext character), we now know what cipher character      //to use.      encode_value = toupper(static_cast<int>(MESSAGETOCIPHER[ix]));      enc_message[ix] = CTEXT[encode_value-SIXTYFIVE];    }  }  //return a reference to the encoded message  return enc_message; }//end formCipheredMessage() //---------------------------------------------------------------- //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: 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) {  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);  cout << endl;  return; }//end getFileNames() //---------------------------------------------------------------- //Function: getKeyword() //Parameters: text - the keyword that the user enters //Return Type: int - the length of the keyword //Purpose: Prompts the user for a keyword and continues until //a valid keyword has been entered.  Returns the length of the //keyword. //---------------------------------------------------------------- int getKeyword(char * &text) {  bool error = false;  char buffer[SIZE];  do {    cout << "Enter keyword or keyword phrase in UPPERCASE" << endl             << "do not use spaces or non-alphabetic characters): ";    cin.getline(buffer, SIZE, '\n');    assert(text = new char[strlen(buffer) + 1]);    strcpy(text, buffer);    error = checkInput(text);    //delete text if there was an error    if(error){      delete [] text;    }  } while (error);  cout << endl;  return strlen(buffer); }//end getKeyword() //---------------------------------------------------------------- //Function: getMessage() //Parameters:  input - the name of the input plaintext file //      output the name of the output ciphertext file //      msg_to_cipher - the message to be encoded //      PTEXT[] - the plaintext alphabet //      CTEXT[] - the ciphertext alphabet //Return Type: bool, indicating success of operation //Purpose: Allow the user to manually input text from the keyboard. //Save the text in plaintext to the input file; encrypt the text //and save it to the specified output file for later retrieval. //---------------------------------------------------------------- bool getMessage(char* input, char* output, char msg_to_cipher[],                   const char PTEXT[],          const char CTEXT[]) {  bool go_on = true, success = false;  ofstream textFile(input, ios::app);  ofstream cipherFile(output, ios::app);  if((!textFile) || (!cipherFile)){    //do nothing - error will be noted to user later  }  else {    success = true;    textFile << "PLAINTEXT:  " << PTEXT << endl;    textFile << "CIPHERTEXT: " << CTEXT << endl << endl;    //get the newline character off of the input stream    cin.get();    cout << "Enter the message in UPPERCASE characters: " << endl;    while (go_on) {     //get the entire line, up to 256 characters     cin.getline(msg_to_cipher, SIZE, '\n');     //case user doesn't want the text to be encrypted     if(msg_to_cipher[0] == '/'){       if(strlen(BUFFER)>0){         //empty whatever is in the buffer         groupBUFFER(cipherFile, strlen(BUFFER));         //adjust the buffer         strcpy(BUFFER, (BUFFER+strlen(BUFFER)));       }       //output plaintext       textFile << msg_to_cipher << endl;       cipherFile << msg_to_cipher << endl;       }     //case user is done entering text     else if (static_cast<int>(msg_to_cipher[0]) == NINETYTWO){       go_on = false;       }     //encrypt the text     else {       textFile << msg_to_cipher << endl;       char enciphered_msg[BIGSIZE];       formCipheredMessage(CTEXT,msg_to_cipher,enciphered_msg);       printCipherToFile(cipherFile,enciphered_msg);       }     }  //empty the rest of the buffer  groupBUFFER(cipherFile, strlen(BUFFER));  }  //close the files  textFile.close();  cipherFile.close();  //notify user where plaintext and ciphertext files are  cout << "\nPlaintext file is: " << input << endl;  cout << "Encrypted file is: " << output << endl << endl;  return success; }//end getMessage() //---------------------------------------------------------------- //Function: getShiftKey() //Parameters:  key_desired - uppercase key entered by the user //Return Type: None //Purpose: Get the key the user enters; error checking performed //until user enters a valid value. //---------------------------------------------------------------- void getShiftKey(char &key_desired) {  bool error = true;  do {   //prompt user to enter an uppercase shift key   cout << "Enter UPPERCASE Alphabetic Shift Key (CTRL-C to quit): ";   cin >> key_desired;   int key_value = static_cast<int>(key_desired);   //do some error checking   if((key_value < SIXTYFIVE) || (key_value > NINETY)){     cerr << "\nYou must enter a letter from A to Z!" << endl << endl;   }   else {     cout << endl;     error = false;    }   } while (error);   return; }//end getShiftKey() //---------------------------------------------------------------- //Function: groupBUFFER() //Parameters: out - the output stream we are writing to //      num - the number of characters we want to output //Return Type: None //Purpose: Output the buffer in groups of five characters at a //time. //---------------------------------------------------------------- void groupBUFFER(ofstream out, int num) {  for(int kx=0;kx<num;kx++){    if((kx!=0) && (kx%TWENTYFIVE==0)){      out << endl;    }    if((kx!=0) && (kx%FIVE == 0) && (kx%TWENTYFIVE!=0)){       out << " " << *(BUFFER+kx);    }    else {         out << *(BUFFER+kx);    }  }  out << endl;  return; }//end groupBUFFER() //---------------------------------------------------------------- //Function: interval() //Parameters:  ctext - the cipher stream we are modifying //Return Type: None //Purpose: Create the cipher stream based on interval extraction. //---------------------------------------------------------------- void interval(char ctext[]) {   int interval, pos;   char temp[TWENTYSEVEN];   cout << "Enter the interval as a numeric between 1 and 25: ";   cin >> interval;   while ((interval < ONE) || (interval > TWENTYFIVE)){    cerr << "\aInterval must be between 1 and 25." << endl;    cerr << "Enter interval: ";    cin >> interval;   }   for(int ix=0; ix<TWENTYSIX; ix++)     temp[ix] = ctext[ix];   for(int jx=0; jx<TWENTYSIX; jx++){     pos = (((jx+1)*interval)-1)%TWENTYSIX;     ctext[jx] = temp[pos];   }   cout << "\nInterval-based alphabet is " << ctext << endl << endl;   return; }//end interval() //---------------------------------------------------------------- //Function: numericExtraction() //Parameters: MATRIX - the matrix we want to form the cipher from //      cipher - the cipher stream we will create //      R - the number of rows in the matrix //      C - the number of columns in the matrix //Return Type: None //Purpose: Creates the cipher stream we will use to encrypt files //by pulling off the columns from the matrix in alphabetical order //based on the character in the top row, and inserting them into //the cipher array. //---------------------------------------------------------------- void numericExtraction(char **& MATRIX, char cipher[], const int R,                            const int C) {   int counter = 0;   //place ASCII values of first row's characters into a table;   //we will use these values to determine the order in which   //we pull columns out of the matrix   int *top_row_ASCII_values = new int[C];   assert(top_row_ASCII_values);   //no cast to integer type required since this is already taken   //care of for us   for (int ix=0; ix<C; ix++){     *(top_row_ASCII_values + ix) = *((*MATRIX)+ix);   }   for(int jx=0; jx<C; jx++){     //find out what column we want     int col = findLowestValue(top_row_ASCII_values, C);     //put contents of the column into the cipher stream, but     //only do this when we have a character!     for(int kx=0; kx<R; kx++){        if((*(*(MATRIX+kx)+col)) != '\0'){          cipher[counter++] = (*(*(MATRIX+kx)+col));        }      }   }   //destroy dynamically allocated memory   delete [] top_row_ASCII_values;   return; }//end numericExtraction() //---------------------------------------------------------------- //Function: printCipherToFile() //Parameters: op - the output file we are writing to //            msg - the cipher text we are displaying //Return Type: None //Purpose: Group the cipher in 5-block characters in the //specified output file. //---------------------------------------------------------------- void printCipherToFile(ofstream op, char msg[]){   formatData(msg);   //check to see if there are more than 25 characters   //in the buffer; if so, print out as many groups of   //25 as possible   if(strlen(BUFFER) >= TWENTYFIVE){      int numchars = (strlen(BUFFER)/TWENTYFIVE)*TWENTYFIVE;      //print the contents of the buffer to the output stream      groupBUFFER(op, numchars);      //shift whatever is left in the buffer      strcpy(BUFFER, (BUFFER+numchars));      //append data to the buffer      strcat(BUFFER, msg);   }   //if buffer contents are less than 25, simply append the new   //data to the buffer   else if ((strlen(BUFFER) >= 0) && (strlen(BUFFER) < TWENTYFIVE)){     strcat(BUFFER, msg);   }   return; }//end printCipherToFile() //---------------------------------------------------------------- //Function: printMatrix() //Parameters: the_matrix - the matrix we want to display //      ROWS - the number of rows in the matrix //      COLS - the number of columns in the matrix //Return Type: None //Purpose: Displays the matrix. //---------------------------------------------------------------- void printMatrix(char ** &the_matrix, const int ROWS, const int COLUMNS) {   cout << "\nThe matrix is:" << endl << endl;   for(int ix=0; ix<ROWS; ix++){     for(int kx=0; kx<COLUMNS; kx++){       cout << *(*(the_matrix+ix)+kx) << " ";     }     cout << endl;   }   return; }//end printMatrix() //---------------------------------------------------------------- //Function: reviseCipherStream() //Parameters: MATRIX - the numeric keyed transposed matrix //      cipher - the cipher stream that was originally created //           when the user entered a keyword //      R - the number of rows in the matrix //      C - the number of columns in the matrix //Return Type: None //Purpose: Overwrites the cipher stream initially created with the //one we get by taking columns out of the matrix. //---------------------------------------------------------------- void reviseCipherStream(char ** &MATRIX, char cipher[], const int R,                 const int C, const int enc_type) {   if(enc_type == TWO){      simpleExtraction(MATRIX, cipher, R, C);   }   else {     numericExtraction(MATRIX, cipher, R, C);   }   //print the resulting matrix   printMatrix(MATRIX, R, C);   if(enc_type == TWO)     cout << "\nSIMPLE Transposition alphabet is: " << cipher << endl               << endl;   else     cout << "\nNUMERIC Transposition alphabet is: " << cipher << endl                       << endl;   return; }//end reviseCipherStream() //---------------------------------------------------------------- //Function: shiftKeyword() //Parameters: ctext - the cipher alphabet we are going to shift //      user_key - the key the user entered //Return Type: None //Purpose: Shift the keyword or keyword phrase we will use later to //encode the user's message. //---------------------------------------------------------------- void shiftKeyword(char ctext[], const char USER_KEY) {   int location;   char temp[TWENTYSIX] = {'\0'};   //find the location of the key in the plaintext   for(int ix=0; ix<TWENTYSIX; ix++){      if(USER_KEY == ctext[ix]){        location = ix;        break;      }   }   if (location == TWENTYFIVE){           //do nothing   }   else {      //put into temp all the characters up to and including the shift key      //location now indicated how many characters, so we must increment by      //one since the array uses a zero-based index      strncpy(temp, ctext, location+1);      //shift all remaining characters in the ciphertext      strcpy(ctext, (ctext+location+1));      //concatenate temp back to ctext      strcat(ctext, temp);   }   cout << "Shifted keyword-mixed alphabet is: " << ctext << endl << endl;   return; }//end shiftKeyword(); //---------------------------------------------------------------- //Function: simpleExtraction() //Parameters: MATRIX - the matrix we want to form the cipher from //      cipher - the cipher stream we will create //      R - the number of rows in the matrix //      C - the number of columns in the matrix //Return Type: None //Purpose: Creates the cipher stream we will use to encrypt files //by pulling off the columns from left to right and inserting them //into the cipher array. //---------------------------------------------------------------- void simpleExtraction(char **& MATRIX, char cipher[], const int R,                            const int C) {   int counter = 0;   for (int ix=0; ix<C; ix++){      for (int kx=0; kx<R; kx++){         if ((*(*(MATRIX+kx)+ix)) != '\0'){            cipher[counter++] = (*(*(MATRIX+kx)+ix));            }      }   }   return; }//end simpleExtraction() //---------------------------------------------------------------- //Function: welcome() //Parameters:  None //Return Type: int - method the cipher stream will be created; //1 is interval, 2 is simple, 3 is numeric //Purpose: Allow the user to select which method he/she wants //to use to create the cipher stream. //---------------------------------------------------------------- int welcome() {   int type;   cout << "Program cipher6.cpp enciphers a message using one" << endl      << "of the following techniques to form a cipher alphabet:"                         << endl << endl         << "(1) Interval Extraction Sequence" << endl         << "(2) Simple Transposition Sequence" << endl         << "(3) Numeric Transposition Sequence" << endl << endl         << "Enter method to form enciphered message 1, 2 or 3: ";   cin >> type;   while ((type <ONE) || (type > THREE)){    cerr << "\aYou must enter a number between 1 and 3!" << endl;    cerr << "Choice: ";    cin >> type;   }   //get the newline off the stream   cin.get();   cout << endl;   return type; }//end welcome() //end file cipher6.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