?
Solved

Caeser Cipher

Posted on 2006-03-29
11
Medium Priority
?
649 Views
Last Modified: 2008-01-09
Looking for Caeser cipher model for:

 1. Encrytion
 2. Decryption
 3. Quit            

for text string.
0
Comment
Question by:edelossantos
10 Comments
 
LVL 12

Assisted Solution

by:rajeev_devin
rajeev_devin earned 200 total points
ID: 16329451
0
 
LVL 53

Expert Comment

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

Author Comment

by:edelossantos
ID: 16334953
I have a basic idea for the code, I will submit it to see if I am on the rite track.
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 53

Expert Comment

by:Infinity08
ID: 16340103
Good, We'll be waiting for that to help you further if needed.
0
 

Author Comment

by:edelossantos
ID: 16353300
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;

}

******************************************
0
 

Author Comment

by:edelossantos
ID: 16353320
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;

}
0
 
LVL 53

Assisted Solution

by:Infinity08
Infinity08 earned 300 total points
ID: 16358321
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 !!
0
 

Author Comment

by:edelossantos
ID: 16364748
>> void Cypher::quit() {
>>   exit(-1);
>> }

quit program.
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 16368175
I meant the method before my comment : the moveFile() method
0
 
LVL 39

Accepted Solution

by:
itsmeandnobodyelse earned 500 total points
ID: 16393717
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
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

807 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question