We help IT Professionals succeed at work.

Caeser Cipher

edelossantos
edelossantos asked
on
Medium Priority
666 Views
Last Modified: 2008-01-09
Looking for Caeser cipher model for:

 1. Encrytion
 2. Decryption
 3. Quit            

for text string.
Comment
Watch Question

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
CERTIFIED EXPERT
Top Expert 2009

Commented:
The Caesar Cipher algorithm is pretty easy, as shown in the link rajeev_devin gave ... Do you have a specific problem with the implementation ?

Author

Commented:
I have a basic idea for the code, I will submit it to see if I am on the rite track.
CERTIFIED EXPERT
Top Expert 2009

Commented:
Good, We'll be waiting for that to help you further if needed.

Author

Commented:
Ok, here is my attempt at the code, please advise.  Del

*************************code************************************

/*
Code Specifications:
1. Write a class basd C++ program to implement the Caeser cipher based algorithm
for encrypting and decryting text messages. Test your program for the following
text string:  "IDESOFMARCH".

Your program should read the text string, for encryption or decryption, from a file
and save the result in a different file. Your program should also allow the user to
instruct the program to perform either encryption or decryption task at a tme by
making use of the following menu:

     1. Encrytion
     2. Decryption
     3. Quit
*/
#include <iostream>
#include <ctype.h>

using namespace std;

class Cypher {

public:
      
      String Cypher(String&, int);
      ~String Cypher();
      char EncryptPassword(char *);
      char DecryptPassword(char *);
      void displayPasswords();
      void moveFile(char *, char *, int);
      void quit();       


private:

      int FirstPrintableChar, NumPrintableChar;

};

Cypher::String Cypher(String& S, int l)
{
        const int                    
                FirstPrintableChar = 32,  
                     /*printable range is 32 thru 126*/
                NumPrintableChars = 95;    

        while (l < 0)   /*if k is negative, % wont work*/
                l += NumPrintableChars; /*get the range to 0 - 94*/

        int LengthA = S.Length();
        char *Word = S.c_str();
                    /*convert your str to a char*/
       

        for (int i = 0; i < LengthA; i++)    
                    /*for each char in the string:*/
        {

                if (isprint(Word[i]))  /*if its 32-126,*/
                        Word[i] =
                        ((((Word[i] - FirstPrintableChar)
            /*scale into 0 - 94*/
                        + l)       /*add the offset*/
                        % NumPrintableChars)  
/*wrap around and scale back into 32-126*/
                        + FirstPrintableChar);

        }
        S = Word;          /*convert back into a string*/
        return (S);        /*return the value*/

}

// encrypt a password from text to add-index
char Cypher::EncryptPassword(char *inPasswd)
{
    static char pwBuffer[64];
    int w, x;
    // init
    memset(pwBuffer, 0, sizeof(pwBuffer));
    x = strlen(inPasswd);
    if (x > 0)
    {   // loop through the string, adding the index
        for (w = 0; w < x; w++)
            pwBuffer[w] = (char)(inPasswd[w] + (w + 1));
    }
    return(pwBuffer);
}
 
// decrypt a password from text that was add-index encrypted
char Cypher::DecryptPassword(char *inPasswd)
{
    static char pwBuffer[64];
    int w, x;
    // init

    memset(pwBuffer, 0, sizeof(pwBuffer));
    x = strlen(inPasswd);
    if (x > 0)
    {   // loop through the string, subtracting the index
        for (w = 0; w < x; w++)
            pwBuffer[w] = (char)(inPasswd[w] - (w + 1));
    }
    return(pwBuffer);
}

void Cypher::displayPasswords() {

      cout << EncryptPassword << DecryptPassword << endl;

}

void moveFile(char *from, char *to, int move, ofstream * outFile) {

     cout << move << "  Move File from "<< from << " to "<< to << endl;
     *outFile << move << "  Move File from "<< from << " to "<< to;
}

void Cypher::quit() {

      exit(-1);

}



int main() {

      Cypher c;
      c.EncryptPassword();
      c.DecryptPassword();

      c.displayPasswords();

      char *line = "";
    char *fname = "output.doc";

      // Opens the output file
    ofstream outFile(fname, ios::out);

      return 0;

}

******************************************

Author

Commented:
Update:

      
Comment from rajeev_devin
Date: 03/29/2006 09:12PM PST
      Comment       Accept

Here is one link
http://en.wikipedia.org/wiki/Caesar_cipher

Comment from Infinity08
Date: 03/29/2006 11:28PM PST
      Comment       Accept

The Caesar Cipher algorithm is pretty easy, as shown in the link rajeev_devin gave ... Do you have a specific problem with the implementation ?

Comment from edelossantos
Date: 03/30/2006 10:01AM PST
      Your Comment       

I have a basic idea for the code, I will submit it to see if I am on the rite track.

Comment from Infinity08
Date: 03/30/2006 11:09PM PST
      Comment       Accept

Good, We'll be waiting for that to help you further if needed.

Comment from edelossantos
Date: 04/01/2006 11:21PM PST
      Your Comment       

Ok, here is my attempt at the code, please advise.  Del

*************************code************************************

/*
Code Specifications:
1. Write a class basd C++ program to implement the Caeser cipher based algorithm
for encrypting and decryting text messages. Test your program for the following
text string:  "IDESOFMARCH".

Your program should read the text string, for encryption or decryption, from a file
and save the result in a different file. Your program should also allow the user to
instruct the program to perform either encryption or decryption task at a tme by
making use of the following menu:

     1. Encrytion
     2. Decryption
     3. Quit
*/
#include <iostream>
#include <ctype.h>

using namespace std;

class Cypher {

public:
     
     String Cypher(String&, int);
     ~String Cypher();
     char EncryptPassword(char *);
     char DecryptPassword(char *);
     void displayPasswords();
     void moveFile(char *, char *, int);
     void quit();      


private:

     int FirstPrintableChar, NumPrintableChar;

};

Cypher::String Cypher(String& S, int l)
{
        const int                    
                FirstPrintableChar = 32,  
                     /*printable range is 32 thru 126*/
                NumPrintableChars = 95;    

        while (l < 0)   /*if k is negative, % wont work*/
                l += NumPrintableChars; /*get the range to 0 - 94*/

        int LengthA = S.Length();
        char *Word = S.c_str();
                    /*convert your str to a char*/
       

        for (int i = 0; i < LengthA; i++)    
                    /*for each char in the string:*/
        {

                if (isprint(Word[i]))  /*if its 32-126,*/
                        Word[i] =
                        ((((Word[i] - FirstPrintableChar)
            /*scale into 0 - 94*/
                        + l)       /*add the offset*/
                        % NumPrintableChars)  
/*wrap around and scale back into 32-126*/
                        + FirstPrintableChar);

        }
        S = Word;          /*convert back into a string*/
        return (S);        /*return the value*/

}

// encrypt a password from text to add-index
char Cypher::EncryptPassword(char *inPasswd)
{
    static char pwBuffer[64];
    int w, x;
    // init
    memset(pwBuffer, 0, sizeof(pwBuffer));
    x = strlen(inPasswd);
    if (x > 0)
    {   // loop through the string, adding the index
        for (w = 0; w < x; w++)
            pwBuffer[w] = (char)(inPasswd[w] + (w + 1));
    }
    return(pwBuffer);
}
 
// decrypt a password from text that was add-index encrypted
char Cypher::DecryptPassword(char *inPasswd)
{
    static char pwBuffer[64];
    int w, x;
    // init

    memset(pwBuffer, 0, sizeof(pwBuffer));
    x = strlen(inPasswd);
    if (x > 0)
    {   // loop through the string, subtracting the index
        for (w = 0; w < x; w++)
            pwBuffer[w] = (char)(inPasswd[w] - (w + 1));
    }
    return(pwBuffer);
}

void Cypher::displayPasswords() {

     cout << EncryptPassword << DecryptPassword << endl;

}

void moveFile(char *from, char *to, int move, ofstream * outFile) {

     cout << move << "  Move File from "<< from << " to "<< to << endl;
     *outFile << move << "  Move File from "<< from << " to "<< to;
}

void Cypher::quit() {

     exit(-1);

}



int main() {

     Cypher c;
     c.EncryptPassword();
     c.DecryptPassword();

     c.displayPasswords();

     char *line = "";
    char *fname = "outfile.txt";

     // Opens the output file
    ofstream outFile(fname, ios::out);

     return 0;

}
CERTIFIED EXPERT
Top Expert 2009
Commented:
I'll go over the code from start to end, and give comments on parts that deserve a comment :

>>     String Cypher(String&, int);
>>     ~String Cypher();
These are the constructor and destructor for the Cypher class, and can't have a return type ... Just define them like this :

         Cypher(String&, int);
         ~Cypher();

The same for the implementation of the methods of course :

         Cypher::Cypher(String& S, int l) { /* ... */ }
         Cypher::~Cypher() { /* ... */ }


>>     char EncryptPassword(char *);
>>     char DecryptPassword(char *);
I imagine you want to return a string too ? (instead of just a char) ...
Why not use the C++ strings (string) instead of the C strings (char*) ??

>> Cypher::String Cypher(String& S, int l)
>> {
>>         const int                    
>>                 FirstPrintableChar = 32,  
>>                      /*printable range is 32 thru 126*/
>>                 NumPrintableChars = 95;    
Why do you define these as "const int" ? You have two class members with the same name ... didn't you want to use those ?

>>         while (l < 0)   /*if k is negative, % wont work*/
>>                 l += NumPrintableChars; /*get the range to 0 - 94*/
This is OK, but what if l > 94 ?

>>         int LengthA = S.Length();
>>         char *Word = S.c_str();
                    /*convert your str to a char*/
       

>>         return (S);        /*return the value*/
Since the constructor doesn't return anything, drop this !! The problem now of course is, that the calculated string doesn't get returned. There is a problem in your design ... the constructor is used to INITIALIZE the class members etc. To do the actual ENCRYPTING, you'll have to use a separate method of the class :

         char EncryptPassword(char *);


>> // encrypt a password from text to add-index
>> char Cypher::EncryptPassword(char *inPasswd)
>> {
>> ...
>> }
I'm not sure what you're trying to do here, but this is not a normal Caesar crypt ... did you find this code somewhere and paste it in your class ? You already implemented the encryption in your constructor ... all you have to do is move it from the constructor to this method !
 
>> // decrypt a password from text that was add-index encrypted
>> char Cypher::DecryptPassword(char *inPasswd)
>> {
>> ...
>> }
same remark ! Decryption is the opposite of encryption, so you shouldn't have too much trouble implementing it ...

>> void Cypher::displayPasswords() {
>>    cout << EncryptPassword << DecryptPassword << endl;
>> }
You are trying to print two strings to the screen, but where does it get them from ? EncryptPassword and DecryptPassword are not defined in this context !!!

>> void moveFile(char *from, char *to, int move, ofstream * outFile) {
>>   cout << move << "  Move File from "<< from << " to "<< to << endl;
>>   *outFile << move << "  Move File from "<< from << " to "<< to;
>> }
Can you tell me what you are trying to do in this method ?

>> void Cypher::quit() {
>>   exit(-1);
>> }
Basically this is OK, but generally, a quit() method is not really needed in this class ... you can keep it if you want though ...

>> int main() {
>>     Cypher c;
>>     c.EncryptPassword();
>>     c.DecryptPassword();
The EncryptPassword() and DecryptPassword() methods have an argument of type char*. If you use C++ strings instead of char*, then of course you should change this accordingly !



A general comment ... check this page for information on reading from and writing to files :

http://www.cplusplus.com/doc/tutorial/files.html


If you have any questions, or if there is anything that is not clear, then please ask in this thread !! We'll be glad to help you along in this project !!

Author

Commented:
>> void Cypher::quit() {
>> Â  exit(-1);
>> }

quit program.
CERTIFIED EXPERT
Top Expert 2009

Commented:
I meant the method before my comment : the moveFile() method
Del, I would recommend to have a different design for your class. I would think it is better to have two classes. One that implements the Ceasar Cipher and a second that does the dialog and file handling. That allows you to implement additional crypting algorithms if required.

I also strongly recommend to use std::string instead of String (if allowed). Though any string class is better than plain char arrays, life is easier if using a string class that is available everywhere and is included in the C++ standard.

#include <string>
#include <iostream>
#include <fstream>
using namespace std;

class Ceasar
{
     int   ceasar;

     enum { FIRST_PRINTABLE = 32,
                LAST_PRINTABLE = 126,
                NUM_PRINTABLE = LAST_PRINTABLE - FIRST_PRINTABLE + 1
               };
public:
      Ceasar(int ceas);
      string encrypt(const string& plain);
      string decrypt(const string& code);
};

class Cypher
{
     string plainFile;
     string codeFile;
public:
     enum MenuChoice { ENCRYPTION, DECRYPTION, QUIT };

     Cypher(const string& plainFile, const string& codeFile);
     MenuChoice menu();
     string readText( bool encrypted );
     void   writeText(const string& str, bool encrypted );
     void   display(const string& textin, const string& textout, bool encrypting);
};

You would use it like that:

int main()
{
    Cypher cypher("plainpassword.txt", "codedpassword.txt");
    Cypher::MenuChoice choice;
    while ((choice = cypher.menu()) != Cypher::QUIT)
    {
          string in, out;
          Ceasar ceasar(13);  
          if (choice == Cypher::ENCRYPTION)
          {
                in   = cypher.readText(false);  // read plain password
                if (in.empty())
                    continue;           // some error occured in readText
                out = ceasar.encrypt(in);
                cypher.writeText(out, true);
                cypher.display(in, out, true);
          }
          else  /* if (choice == Cypher::DECRYPTION) */
          {
                 // implement that part similar to the one above
                 // switching true/false and encrypt to decrypt
          }
    }
    return 0;
};

Regards, Alex
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.