Simple XOR encryption code issues (segmentation fault)

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • John Williams

    #1

    Simple XOR encryption code issues (segmentation fault)

    I've written a simple program to do XOR encryption as my first foray
    into understanding how encryption works. The code compiles fine, however
    it segmentation faults on every run. using gdb to debug it let me
    narrow the problem down to the Cipher function I think it faults at line
    84 or 85. The program makes it's first read/cipher/write pass without
    issue but the second pass kills it. Using gdb to print the variables
    left showed me the following right before the seg fault.

    i == 1
    j == 1

    *buffer[0] contains ciphered text from the previous pass
    *buffer[1] "Cannot access memory at address ..."
    *buffer[2] random values (uninitialized. ..however the memory is able to
    be accessed)

    I can't figure out why *buffer[1] would be inaccessible with my code and
    would appreciate some help figuring out my error.
  • John Williams

    #2
    Re: Simple XOR encryption code issues (segmentation fault)

    oops forgot to attach my code




    /* A simple implementation of a XOR encryption algorithm. Not terribly secure, but
    * fast and easy to use. Written as a basic learning exercise in the basics of
    * encryption this should only be used for study or for the most basic of
    * encryption as XOR is easily defeated*/

    //Written by Jaidan (John Williams) 3/11/07

    #include <stdio.h>
    #include <iostream>
    #include <fstream>
    #include <time.h>
    #include <math.h>

    using namespace std;

    void Cipher(char key[], char inname[], char outname[]);
    void keymaker(char key[]);
    int filesizer(fstre am *file);

    int main()
    {
    /* main gathers the basic starting information, the filenames and key to be used and
    * calls the appropriate functions based on user input*/

    int booltest;
    char key[8], inname[21], outname[21];

    cout << "Please type input filename: ";
    cin >inname;
    cout << "Please type output filename: ";
    cin >outname;
    cout << "Would you like to use the auto keygen (1 for yes / 2 for no)?";
    cin >booltest;
    cout << endl;

    if (booltest == 1) {
    keymaker(key);
    Cipher(key, inname, outname);
    }
    else if (booltest == 2) {
    cout << "Please type desired 8 digit key: ";
    cin >key;
    cout << endl;
    Cipher(key, inname, outname);
    }
    cout << "Process completed!\n";
    return 0;

    }

    void keymaker(char key[8])
    {
    /* Generates a random key for use in the encryption, as the characters allowed are
    * kinda wide and therefore the key will be hard to remember (type?)*/
    int i, random;
    srand(time(NULL ));

    for (i = 0; i < 8; i++) {

    key[i] = ((rand() % 87) +35);// generates a limited random ascii char
    }
    cout << "The key that will be used is: " << key << endl;
    return;
    }
    void Cipher(char key[], char inname[], char outname[])
    {
    /*XOR encryption/decipher algorithm. takes input from a specified input file and
    * outputs it to a specified output file. Due to the nature of XOR encryption this
    * algorithm handles both the encryption and deciphering of the data*/

    int i, j, block, ArraySize, filesize;
    char *buffer[8];
    fstream infile, outfile;

    infile.open(inn ame, ios::in);
    outfile.open(ou tname, ios::out | ios::trunc);
    filesize = filesizer(&infi le);

    for (i = 0, j = 0; i < filesize; j++, i++) {
    if (j >= (7)) { // Reset the key to the begining
    j = 0;
    outfile.write(* buffer, 8); // Purge buffer to file
    }
    infile.seekg(i) ; //sets the get pointed to the current reference
    infile.read(buf fer[j],1); //Read the current data at the get pointer
    *buffer[j] = *buffer[j]^key[j]; //XOR encrypt/decrypt the current data
    }
    return;
    }

    int filesizer(fstre am *file)
    {
    /*Determines the file size by seeking the end of the file*/
    int size;

    file->seekg(0, ios::end);
    size = file->tellg();
    file->seekg(0);
    return size;
    }

    Comment

    • gethostbyname@gmail.com

      #3
      Re: Simple XOR encryption code issues (segmentation fault)

      On 11 mar, 20:23, John Williams <druidjai...@gm ail.comwrote:
      oops forgot to attach my code
      >
      [jxorcrypt.cpp]/* A simple implementation of a XOR encryption algorithm. Not terribly secure, but
      * fast and easy to use. Written as a basic learning exercise in the basics of
      * encryption this should only be used for study or for the most basic of
      * encryption as XOR is easily defeated*/
      >
      //Written by Jaidan (John Williams) 3/11/07
      >
      #include <stdio.h>
      #include <iostream>
      #include <fstream>
      #include <time.h>
      #include <math.h>
      >
      using namespace std;
      >
      void Cipher(char key[], char inname[], char outname[]);
      void keymaker(char key[]);
      int filesizer(fstre am *file);
      >
      int main()
      {
      /* main gathers the basic starting information, the filenames and key to be used and
      * calls the appropriate functions based on user input*/
      >
      int booltest;
      char key[8], inname[21], outname[21];
      >
      cout << "Please type input filename: ";
      cin >inname;
      cout << "Please type output filename: ";
      cin >outname;
      cout << "Would you like to use the auto keygen (1 for yes / 2 for no)?";
      cin >booltest;
      cout << endl;
      >
      if (booltest == 1) {
      keymaker(key);
      Cipher(key, inname, outname);
      }
      else if (booltest == 2) {
      cout << "Please type desired 8 digit key: ";
      cin >key;
      cout << endl;
      Cipher(key, inname, outname);
      }
      cout << "Process completed!\n";
      return 0;
      >
      }
      >
      void keymaker(char key[8])
      {
      /* Generates a random key for use in the encryption, as the characters allowed are
      * kinda wide and therefore the key will be hard to remember (type?)*/
      int i, random;
      srand(time(NULL ));
      >
      for (i = 0; i < 8; i++) {
      >
      key[i] = ((rand() % 87) +35);// generates a limited random ascii char
      }
      cout << "The key that will be used is: " << key << endl;
      return;}
      >
      void Cipher(char key[], char inname[], char outname[])
      {
      /*XOR encryption/decipher algorithm. takes input from a specified input file and
      * outputs it to a specified output file. Due to the nature of XOR encryption this
      * algorithm handles both the encryption and deciphering of the data*/
      >
      int i, j, block, ArraySize, filesize;
      char *buffer[8];
      fstream infile, outfile;
      >
      infile.open(inn ame, ios::in);
      outfile.open(ou tname, ios::out | ios::trunc);
      filesize = filesizer(&infi le);
      >
      for (i = 0, j = 0; i < filesize; j++, i++) {
      if (j >= (7)) { // Reset the key to the begining
      j = 0;
      outfile.write(* buffer, 8); // Purge buffer to file
      }
      infile.seekg(i) ; //sets the get pointed to the current reference
      infile.read(buf fer[j],1); //Read the current data at the get pointer
      *buffer[j] = *buffer[j]^key[j]; //XOR encrypt/decrypt the current data
      }
      return;
      >
      }
      >
      int filesizer(fstre am *file)
      {
      /*Determines the file size by seeking the end of the file*/
      int size;
      >
      file->seekg(0, ios::end);
      size = file->tellg();
      file->seekg(0);
      return size;
      >
      }
      There is a problem in this line:
      infile.read(buf fer[j],1); //Read the current data at the get

      This is my proposed modifications:

      void Cipher(char key[], char inname[], char outname[])
      {
      /*XOR encryption/decipher algorithm. takes input from a specified
      input file and
      * outputs it to a specified output file. Due to the nature of XOR
      encryption this
      * algorithm handles both the encryption and deciphering of the data*/

      int i, j, block, ArraySize, filesize;
      char buffer[8];
      fstream infile, outfile;

      infile.open(inn ame, ios::in);
      outfile.open(ou tname, ios::out | ios::trunc);
      filesize = filesizer(&infi le);

      for (i = 0, j = 0; i < filesize; j++, i++) {
      if (j >= (7)) { // Reset the key to the begining
      j = 0;
      outfile.write(b uffer, 8); // Purge buffer to
      file
      }
      infile.seekg(i) ; //sets the get pointed to the
      current reference
      infile.read(&bu ffer[j],1); //Read the current data at
      the get pointer
      buffer[j] = buffer[j]^key[j]; //XOR encrypt/decrypt
      the current data
      }
      return;

      }

      Of course, you can change your code in others ways. Is it generating
      the expected file correctly now?

      gethostbyname

      Comment

      • gethostbyname@gmail.com

        #4
        Re: Simple XOR encryption code issues (segmentation fault)

        On 11 mar, 20:23, John Williams <druidjai...@gm ail.comwrote:
        oops forgot to attach my code
        >
        [jxorcrypt.cpp]/* A simple implementation of a XOR encryption algorithm. Not terribly secure, but
        * fast and easy to use. Written as a basic learning exercise in the basics of
        * encryption this should only be used for study or for the most basic of
        * encryption as XOR is easily defeated*/
        >
        //Written by Jaidan (John Williams) 3/11/07
        >
        #include <stdio.h>
        #include <iostream>
        #include <fstream>
        #include <time.h>
        #include <math.h>
        >
        using namespace std;
        >
        void Cipher(char key[], char inname[], char outname[]);
        void keymaker(char key[]);
        int filesizer(fstre am *file);
        >
        int main()
        {
        /* main gathers the basic starting information, the filenames and key to be used and
        * calls the appropriate functions based on user input*/
        >
        int booltest;
        char key[8], inname[21], outname[21];
        >
        cout << "Please type input filename: ";
        cin >inname;
        cout << "Please type output filename: ";
        cin >outname;
        cout << "Would you like to use the auto keygen (1 for yes / 2 for no)?";
        cin >booltest;
        cout << endl;
        >
        if (booltest == 1) {
        keymaker(key);
        Cipher(key, inname, outname);
        }
        else if (booltest == 2) {
        cout << "Please type desired 8 digit key: ";
        cin >key;
        cout << endl;
        Cipher(key, inname, outname);
        }
        cout << "Process completed!\n";
        return 0;
        >
        }
        >
        void keymaker(char key[8])
        {
        /* Generates a random key for use in the encryption, as the characters allowed are
        * kinda wide and therefore the key will be hard to remember (type?)*/
        int i, random;
        srand(time(NULL ));
        >
        for (i = 0; i < 8; i++) {
        >
        key[i] = ((rand() % 87) +35);// generates a limited random ascii char
        }
        cout << "The key that will be used is: " << key << endl;
        return;}
        >
        void Cipher(char key[], char inname[], char outname[])
        {
        /*XOR encryption/decipher algorithm. takes input from a specified input file and
        * outputs it to a specified output file. Due to the nature of XOR encryption this
        * algorithm handles both the encryption and deciphering of the data*/
        >
        int i, j, block, ArraySize, filesize;
        char *buffer[8];
        fstream infile, outfile;
        >
        infile.open(inn ame, ios::in);
        outfile.open(ou tname, ios::out | ios::trunc);
        filesize = filesizer(&infi le);
        >
        for (i = 0, j = 0; i < filesize; j++, i++) {
        if (j >= (7)) { // Reset the key to the begining
        j = 0;
        outfile.write(* buffer, 8); // Purge buffer to file
        }
        infile.seekg(i) ; //sets the get pointed to the current reference
        infile.read(buf fer[j],1); //Read the current data at the get pointer
        *buffer[j] = *buffer[j]^key[j]; //XOR encrypt/decrypt the current data
        }
        return;
        >
        }
        >
        int filesizer(fstre am *file)
        {
        /*Determines the file size by seeking the end of the file*/
        int size;
        >
        file->seekg(0, ios::end);
        size = file->tellg();
        file->seekg(0);
        return size;
        >
        }
        Remember you are using a mixture of C++ iostreams with C design code.
        It isn't good.


        Hey, why the parenthesis involving the digit?
        " if (j >= (7)) {"


        PS. forgive my english

        gethostbyname

        Comment

        • gethostbyname@gmail.com

          #5
          Re: Simple XOR encryption code issues (segmentation fault)

          On 11 mar, 20:23, John Williams <druidjai...@gm ail.comwrote:
          oops forgot to attach my code
          >
          [jxorcrypt.cpp]/* A simple implementation of a XOR encryption algorithm. Not terribly secure, but
          * fast and easy to use. Written as a basic learning exercise in the basics of
          * encryption this should only be used for study or for the most basic of
          * encryption as XOR is easily defeated*/
          >
          //Written by Jaidan (John Williams) 3/11/07
          >
          #include <stdio.h>
          #include <iostream>
          #include <fstream>
          #include <time.h>
          #include <math.h>
          >
          using namespace std;
          >
          void Cipher(char key[], char inname[], char outname[]);
          void keymaker(char key[]);
          int filesizer(fstre am *file);
          >
          int main()
          {
          /* main gathers the basic starting information, the filenames and key to be used and
          * calls the appropriate functions based on user input*/
          >
          int booltest;
          char key[8], inname[21], outname[21];
          >
          cout << "Please type input filename: ";
          cin >inname;
          cout << "Please type output filename: ";
          cin >outname;
          cout << "Would you like to use the auto keygen (1 for yes / 2 for no)?";
          cin >booltest;
          cout << endl;
          >
          if (booltest == 1) {
          keymaker(key);
          Cipher(key, inname, outname);
          }
          else if (booltest == 2) {
          cout << "Please type desired 8 digit key: ";
          cin >key;
          cout << endl;
          Cipher(key, inname, outname);
          }
          cout << "Process completed!\n";
          return 0;
          >
          }
          >
          void keymaker(char key[8])
          {
          /* Generates a random key for use in the encryption, as the characters allowed are
          * kinda wide and therefore the key will be hard to remember (type?)*/
          int i, random;
          srand(time(NULL ));
          >
          for (i = 0; i < 8; i++) {
          >
          key[i] = ((rand() % 87) +35);// generates a limited random ascii char
          }
          cout << "The key that will be used is: " << key << endl;
          return;}
          >
          void Cipher(char key[], char inname[], char outname[])
          {
          /*XOR encryption/decipher algorithm. takes input from a specified input file and
          * outputs it to a specified output file. Due to the nature of XOR encryption this
          * algorithm handles both the encryption and deciphering of the data*/
          >
          int i, j, block, ArraySize, filesize;
          char *buffer[8];
          fstream infile, outfile;
          >
          infile.open(inn ame, ios::in);
          outfile.open(ou tname, ios::out | ios::trunc);
          filesize = filesizer(&infi le);
          >
          for (i = 0, j = 0; i < filesize; j++, i++) {
          if (j >= (7)) { // Reset the key to the begining
          j = 0;
          outfile.write(* buffer, 8); // Purge buffer to file
          }
          infile.seekg(i) ; //sets the get pointed to the current reference
          infile.read(buf fer[j],1); //Read the current data at the get pointer
          *buffer[j] = *buffer[j]^key[j]; //XOR encrypt/decrypt the current data
          }
          return;
          >
          }
          >
          int filesizer(fstre am *file)
          {
          /*Determines the file size by seeking the end of the file*/
          int size;
          >
          file->seekg(0, ios::end);
          size = file->tellg();
          file->seekg(0);
          return size;
          >
          }
          Remember you are using a mixture of C++ iostreams with C design code.
          It isn't good.


          Hey, why the parenthesis involving the digit?
          " if (j >= (7)) {"


          PS. forgive my english

          gethostbyname

          Comment

          • John Williams

            #6
            Re: Simple XOR encryption code issues (segmentation fault)

            gethostbyname@g mail.com wrote:
            On 11 mar, 20:23, John Williams <druidjai...@gm ail.comwrote:
            >oops forgot to attach my code
            >>
            >[jxorcrypt.cpp]/* A simple implementation of a XOR encryption algorithm. Not terribly secure, but
            > * fast and easy to use. Written as a basic learning exercise in the basics of
            > * encryption this should only be used for study or for the most basic of
            > * encryption as XOR is easily defeated*/
            >>
            >//Written by Jaidan (John Williams) 3/11/07
            >>
            >#include <stdio.h>
            >#include <iostream>
            >#include <fstream>
            >#include <time.h>
            >#include <math.h>
            >>
            >using namespace std;
            >>
            >void Cipher(char key[], char inname[], char outname[]);
            >void keymaker(char key[]);
            >int filesizer(fstre am *file);
            >>
            >int main()
            >{
            >/* main gathers the basic starting information, the filenames and key to be used and
            > * calls the appropriate functions based on user input*/
            >>
            > int booltest;
            > char key[8], inname[21], outname[21];
            >>
            > cout << "Please type input filename: ";
            > cin >inname;
            > cout << "Please type output filename: ";
            > cin >outname;
            > cout << "Would you like to use the auto keygen (1 for yes / 2 for no)?";
            > cin >booltest;
            > cout << endl;
            >>
            > if (booltest == 1) {
            > keymaker(key);
            > Cipher(key, inname, outname);
            > }
            > else if (booltest == 2) {
            > cout << "Please type desired 8 digit key: ";
            > cin >key;
            > cout << endl;
            > Cipher(key, inname, outname);
            > }
            > cout << "Process completed!\n";
            > return 0;
            >>
            >}
            >>
            >void keymaker(char key[8])
            >{
            >/* Generates a random key for use in the encryption, as the characters allowed are
            > * kinda wide and therefore the key will be hard to remember (type?)*/
            > int i, random;
            > srand(time(NULL ));
            >>
            > for (i = 0; i < 8; i++) {
            >>
            > key[i] = ((rand() % 87) +35);// generates a limited random ascii char
            > }
            > cout << "The key that will be used is: " << key << endl;
            > return;}
            >>
            >void Cipher(char key[], char inname[], char outname[])
            >{
            >/*XOR encryption/decipher algorithm. takes input from a specified input file and
            > * outputs it to a specified output file. Due to the nature of XOR encryption this
            > * algorithm handles both the encryption and deciphering of the data*/
            >>
            > int i, j, block, ArraySize, filesize;
            > char *buffer[8];
            > fstream infile, outfile;
            >>
            > infile.open(inn ame, ios::in);
            > outfile.open(ou tname, ios::out | ios::trunc);
            > filesize = filesizer(&infi le);
            >>
            > for (i = 0, j = 0; i < filesize; j++, i++) {
            > if (j >= (7)) { // Reset the key to the begining
            > j = 0;
            > outfile.write(* buffer, 8); // Purge buffer to file
            > }
            > infile.seekg(i) ; //sets the get pointed to the current reference
            > infile.read(buf fer[j],1); //Read the current data at the get pointer
            > *buffer[j] = *buffer[j]^key[j]; //XOR encrypt/decrypt the current data
            > }
            > return;
            >>
            >}
            >>
            >int filesizer(fstre am *file)
            >{
            >/*Determines the file size by seeking the end of the file*/
            > int size;
            >>
            > file->seekg(0, ios::end);
            > size = file->tellg();
            > file->seekg(0);
            > return size;
            >>
            >}
            >
            There is a problem in this line:
            infile.read(buf fer[j],1); //Read the current data at the get
            >
            This is my proposed modifications:
            >
            void Cipher(char key[], char inname[], char outname[])
            {
            /*XOR encryption/decipher algorithm. takes input from a specified
            input file and
            * outputs it to a specified output file. Due to the nature of XOR
            encryption this
            * algorithm handles both the encryption and deciphering of the data*/
            >
            int i, j, block, ArraySize, filesize;
            char buffer[8];
            fstream infile, outfile;
            >
            infile.open(inn ame, ios::in);
            outfile.open(ou tname, ios::out | ios::trunc);
            filesize = filesizer(&infi le);
            >
            for (i = 0, j = 0; i < filesize; j++, i++) {
            if (j >= (7)) { // Reset the key to the begining
            j = 0;
            outfile.write(b uffer, 8); // Purge buffer to
            file
            }
            infile.seekg(i) ; //sets the get pointed to the
            current reference
            infile.read(&bu ffer[j],1); //Read the current data at
            the get pointer
            buffer[j] = buffer[j]^key[j]; //XOR encrypt/decrypt
            the current data
            }
            return;
            >
            }
            >
            Of course, you can change your code in others ways. Is it generating
            the expected file correctly now?
            >
            gethostbyname
            >
            That worked perfectly to at least allow it to not segmentation fault.
            It produces encrypted text however the decrypting isn't accurate so I
            presume that one of my counters isn't correct logic so I'm going to
            review them and probably have it working in a few minutes. Thank you
            very much for helping get those pointers correct.

            In regard to your other posts the "if (j >= (7))" is just silly as the
            extra parenthesis are not needed. I think they are a remanent of when I
            originally intended the program to be able to accept any key length.

            Comment

            • isoftor

              #7
              Re: Simple XOR encryption code issues (segmentation fault)

              On 3ÔÂ12ÈÕ, ÉÏÎç10ʱ04·Ö, "gethostbyn...@ gmail.com"
              <gethostbyn...@ gmail.comwrote:
              On 11 mar, 20:23, John Williams <druidjai...@gm ail.comwrote:
              >
              >
              >
              >
              >
              oops forgot to attach my code
              >
              [jxorcrypt.cpp]/* A simple implementation of a XOR encryption algorithm.. Not terribly secure, but
              * fast and easy to use. Written as a basic learning exercise in the basics of
              * encryption this should only be used for study or for the most basic of
              * encryption as XOR is easily defeated*/
              >
              //Written by Jaidan (John Williams) 3/11/07
              >
              #include <stdio.h>
              #include <iostream>
              #include <fstream>
              #include <time.h>
              #include <math.h>
              >
              using namespace std;
              >
              void Cipher(char key[], char inname[], char outname[]);
              void keymaker(char key[]);
              int filesizer(fstre am *file);
              >
              int main()
              {
              /* main gathers the basic starting information, the filenames and key to be used and
              * calls the appropriate functions based on user input*/
              >
              int booltest;
              char key[8], inname[21], outname[21];
              >
              cout << "Please type input filename: ";
              cin >inname;
              cout << "Please type output filename: ";
              cin >outname;
              cout << "Would you like to use the auto keygen (1 for yes / 2 for no)?";
              cin >booltest;
              cout << endl;
              >
              if (booltest == 1) {
              keymaker(key);
              Cipher(key, inname, outname);
              }
              else if (booltest == 2) {
              cout << "Please type desired 8 digit key: ";
              cin >key;
              cout << endl;
              Cipher(key, inname, outname);
              }
              cout << "Process completed!\n";
              return 0;
              >
              }
              >
              void keymaker(char key[8])
              {
              /* Generates a random key for use in the encryption, as the characters allowed are
              * kinda wide and therefore the key will be hard to remember (type?)*/
              int i, random;
              srand(time(NULL ));
              >
              for (i = 0; i < 8; i++) {
              >
              key[i] = ((rand() % 87) +35);// generates a limited random ascii char
              }
              cout << "The key that will be used is: " << key << endl;
              return;}
              >
              void Cipher(char key[], char inname[], char outname[])
              {
              /*XOR encryption/decipher algorithm. takes input from a specified input file and
              * outputs it to a specified output file. Due to the nature of XOR encryption this
              * algorithm handles both the encryption and deciphering of the data*/
              >
              int i, j, block, ArraySize, filesize;
              char *buffer[8];
              fstream infile, outfile;
              >
              infile.open(inn ame, ios::in);
              outfile.open(ou tname, ios::out | ios::trunc);
              filesize = filesizer(&infi le);
              >
              for (i = 0, j = 0; i < filesize; j++, i++) {
              if (j >= (7)) { // Reset the key to the begining
              j = 0;
              outfile.write(* buffer, 8); // Purge buffer to file
              }
              infile.seekg(i) ; //sets the get pointed to the current reference
              infile.read(buf fer[j],1); //Read the current data at the get pointer
              *buffer[j] = *buffer[j]^key[j]; //XOR encrypt/decryptthe current data
              }
              return;
              >
              }
              >
              int filesizer(fstre am *file)
              {
              /*Determines the file size by seeking the end of the file*/
              int size;
              >
              file->seekg(0, ios::end);
              size = file->tellg();
              file->seekg(0);
              return size;
              >
              }
              >
              Remember you are using a mixture of C++ iostreams with C design code.
              It isn't good.
              >
              Hey, why the parenthesis involving the digit?
              " if (j >= (7)) {"
              >
              PS. forgive my english
              >
              gethostbyname- Òþ²Ø±»ÒýÓÃÎÄ×Ö -
              >
              - ÏÔʾÒýÓõÄÎÄ×Ö -
              infile.read(buf fer[j],1); //Read the current data at the get pointer
              I think it's right! that is to say that it shuold not be
              "infile.read(&b uffer[j],1);".
              but I find an another error ,when it runs,if you select 2(2 for no),it
              will be wrong.


              Comment

              • Jerry Coffin

                #8
                Re: Simple XOR encryption code issues (segmentation fault)

                In article <Wb0Jh.25179$90 7.3789@newsfe13 .phx>, druidjaidan@gma il.com
                says...

                [ ... ]
                /* A simple implementation of a XOR encryption algorithm. Not terribly secure, but
                * fast and easy to use. Written as a basic learning exercise in the basics of
                * encryption this should only be used for study or for the most basic of
                * encryption as XOR is easily defeated*/
                I'd usually use command line arguments instead of interactive prompts
                and such -- the latter are difficult to write well, and usually a real
                pain to use.

                I'd also tend to structure the program as a whole rather differently:

                #include <fstream>
                #include <algorithm>
                #include <iostream>
                #include <time.h>
                #include <functional>
                #include <iterator>
                #include <ios>
                #include <string>

                // This class implements the actual encryption algorithm.
                // Its function call operator is called once with each input
                // character, so it only works for stream ciphers.
                //
                class xor : public std::binary_fun ction<char, std::string, char{
                std::string key_;
                public:
                xor(std::string const &key) : key_(key) {}

                char operator()(char input) const {
                static int key_pos = -1;
                if (++key_pos key_.length())
                key_pos = 0;

                return input ^ key_[key_pos];
                }
                };

                // pretty much copied from the OP
                std::string gen_key() {
                static const int key_len = 8;

                srand(time(NULL ));
                std::string key;

                for (int i=0; i<key_len; i++)
                key += static_cast<cha r>(rand()%87+35 );
                return key;
                }

                int main(int argc, char **argv) {

                if ( argc < 3 || argc 4) {
                std::cerr << "Usage: xor <input_file<out put_file[key]\n";
                return EXIT_FAILURE;
                }

                std::ifstream infile(argv[1], std::ios::binar y);
                std::ofstream outfile(argv[2], std::ios::binar y);

                infile.unsetf(s td::ios_base:: skipws);

                std::string key;

                // use supplied key or generate a new one.
                if (argc == 4)
                key = std::string(arg v[3]);
                else {
                key = gen_key();
                std::cout << "Key: " << key << "\n";
                }

                // encrypt the data from input to output:
                std::transform(
                std::istream_it erator<char>(in file),
                std::istream_it erator<char>(),
                std::ostream_it erator<char>(ou tfile),
                xor(key));

                return 0;
                }

                This isolates the encryption algorithm from the logic for things like
                opening files and such, making it fairly easy to substitute another
                stream cipher for the Vernam cipher currently being used.

                --
                Later,
                Jerry.

                The universe is a figment of its own imagination.

                Comment

                • John Williams

                  #9
                  Re: Simple XOR encryption code issues (segmentation fault)

                  Jerry Coffin wrote:
                  In article <Wb0Jh.25179$90 7.3789@newsfe13 .phx>, druidjaidan@gma il.com
                  says...
                  >
                  [ ... ]
                  >
                  >/* A simple implementation of a XOR encryption algorithm. Not terribly secure, but
                  > * fast and easy to use. Written as a basic learning exercise in the basics of
                  > * encryption this should only be used for study or for the most basic of
                  > * encryption as XOR is easily defeated*/
                  >
                  I'd usually use command line arguments instead of interactive prompts
                  and such -- the latter are difficult to write well, and usually a real
                  pain to use.
                  >
                  I'd also tend to structure the program as a whole rather differently:
                  >
                  #include <fstream>
                  #include <algorithm>
                  #include <iostream>
                  #include <time.h>
                  #include <functional>
                  #include <iterator>
                  #include <ios>
                  #include <string>
                  >
                  // This class implements the actual encryption algorithm.
                  // Its function call operator is called once with each input
                  // character, so it only works for stream ciphers.
                  //
                  class xor : public std::binary_fun ction<char, std::string, char{
                  std::string key_;
                  public:
                  xor(std::string const &key) : key_(key) {}
                  >
                  char operator()(char input) const {
                  static int key_pos = -1;
                  if (++key_pos key_.length())
                  key_pos = 0;
                  >
                  return input ^ key_[key_pos];
                  }
                  };
                  >
                  // pretty much copied from the OP
                  std::string gen_key() {
                  static const int key_len = 8;
                  >
                  srand(time(NULL ));
                  std::string key;
                  >
                  for (int i=0; i<key_len; i++)
                  key += static_cast<cha r>(rand()%87+35 );
                  return key;
                  }
                  >
                  int main(int argc, char **argv) {
                  >
                  if ( argc < 3 || argc 4) {
                  std::cerr << "Usage: xor <input_file<out put_file[key]\n";
                  return EXIT_FAILURE;
                  }
                  >
                  std::ifstream infile(argv[1], std::ios::binar y);
                  std::ofstream outfile(argv[2], std::ios::binar y);
                  >
                  infile.unsetf(s td::ios_base:: skipws);
                  >
                  std::string key;
                  >
                  // use supplied key or generate a new one.
                  if (argc == 4)
                  key = std::string(arg v[3]);
                  else {
                  key = gen_key();
                  std::cout << "Key: " << key << "\n";
                  }
                  >
                  // encrypt the data from input to output:
                  std::transform(
                  std::istream_it erator<char>(in file),
                  std::istream_it erator<char>(),
                  std::ostream_it erator<char>(ou tfile),
                  xor(key));
                  >
                  return 0;
                  }
                  >
                  This isolates the encryption algorithm from the logic for things like
                  opening files and such, making it fairly easy to substitute another
                  stream cipher for the Vernam cipher currently being used.
                  >
                  Thank you for posting that. I've never taken an actual class in c++ so
                  it's really nice being able to see my program and yours that have almost
                  identical functionality, but yours has greatly improved form,
                  modularism, and safety as an example of how I can improve my style.

                  Comment

                  • John Williams

                    #10
                    Re: Simple XOR encryption code issues (segmentation fault)

                    John Williams wrote:
                    gethostbyname@g mail.com wrote:
                    >On 11 mar, 20:23, John Williams <druidjai...@gm ail.comwrote:
                    >>oops forgot to attach my code
                    >>>
                    >>[jxorcrypt.cpp]/* A simple implementation of a XOR encryption
                    >>algorithm. Not terribly secure, but
                    >> * fast and easy to use. Written as a basic learning exercise in the
                    >>basics of
                    >> * encryption this should only be used for study or for the most
                    >>basic of
                    >> * encryption as XOR is easily defeated*/
                    >>>
                    >>//Written by Jaidan (John Williams) 3/11/07
                    >>>
                    >>#include <stdio.h>
                    >>#include <iostream>
                    >>#include <fstream>
                    >>#include <time.h>
                    >>#include <math.h>
                    >>>
                    >>using namespace std;
                    >>>
                    >>void Cipher(char key[], char inname[], char outname[]);
                    >>void keymaker(char key[]);
                    >>int filesizer(fstre am *file);
                    >>>
                    >>int main()
                    >>{
                    >>/* main gathers the basic starting information, the filenames and key
                    >>to be used and
                    >> * calls the appropriate functions based on user input*/
                    >>>
                    >> int booltest;
                    >> char key[8], inname[21], outname[21];
                    >>>
                    >> cout << "Please type input filename: ";
                    >> cin >inname;
                    >> cout << "Please type output filename: ";
                    >> cin >outname;
                    >> cout << "Would you like to use the auto keygen (1 for yes / 2
                    >>for no)?";
                    >> cin >booltest;
                    >> cout << endl;
                    >>>
                    >> if (booltest == 1) {
                    >> keymaker(key);
                    >> Cipher(key, inname, outname);
                    >> }
                    >> else if (booltest == 2) {
                    >> cout << "Please type desired 8 digit key: ";
                    >> cin >key;
                    >> cout << endl;
                    >> Cipher(key, inname, outname);
                    >> }
                    >> cout << "Process completed!\n";
                    >> return 0;
                    >>>
                    >>}
                    >>>
                    >>void keymaker(char key[8])
                    >>{
                    >>/* Generates a random key for use in the encryption, as the
                    >>characters allowed are
                    >> * kinda wide and therefore the key will be hard to remember (type?)*/
                    >> int i, random;
                    >> srand(time(NULL ));
                    >>>
                    >> for (i = 0; i < 8; i++) {
                    >>>
                    >> key[i] = ((rand() % 87) +35);// generates a limited
                    >>random ascii char
                    >> }
                    >> cout << "The key that will be used is: " << key << endl;
                    >> return;}
                    >>>
                    >>void Cipher(char key[], char inname[], char outname[])
                    >>{
                    >>/*XOR encryption/decipher algorithm. takes input from a specified
                    >>input file and
                    >> * outputs it to a specified output file. Due to the nature of XOR
                    >>encryption this
                    >> * algorithm handles both the encryption and deciphering of the data*/
                    >>>
                    >> int i, j, block, ArraySize, filesize;
                    >> char *buffer[8];
                    >> fstream infile, outfile;
                    >>>
                    >> infile.open(inn ame, ios::in);
                    >> outfile.open(ou tname, ios::out | ios::trunc);
                    >> filesize = filesizer(&infi le);
                    >>>
                    >> for (i = 0, j = 0; i < filesize; j++, i++) {
                    >> if (j >= (7)) { // Reset the key to the begining
                    >> j = 0;
                    >> outfile.write(* buffer, 8); // Purge buffer
                    >>to file
                    >> }
                    >> infile.seekg(i) ; //sets the get pointed to the
                    >>current reference
                    >> infile.read(buf fer[j],1); //Read the current data at
                    >>the get pointer
                    >> *buffer[j] = *buffer[j]^key[j]; //XOR encrypt/decrypt
                    >>the current data
                    >> }
                    >> return;
                    >>>
                    >>}
                    >>>
                    >>int filesizer(fstre am *file)
                    >>{
                    >>/*Determines the file size by seeking the end of the file*/
                    >> int size;
                    >>>
                    >> file->seekg(0, ios::end);
                    >> size = file->tellg();
                    >> file->seekg(0);
                    >> return size;
                    >>>
                    >>}
                    >>
                    >There is a problem in this line:
                    > infile.read(buf fer[j],1); //Read the current data at the get
                    >>
                    >This is my proposed modifications:
                    >>
                    >void Cipher(char key[], char inname[], char outname[])
                    >{
                    >/*XOR encryption/decipher algorithm. takes input from a specified
                    >input file and
                    > * outputs it to a specified output file. Due to the nature of XOR
                    >encryption this
                    > * algorithm handles both the encryption and deciphering of the data*/
                    >>
                    > int i, j, block, ArraySize, filesize;
                    > char buffer[8];
                    > fstream infile, outfile;
                    >>
                    > infile.open(inn ame, ios::in);
                    > outfile.open(ou tname, ios::out | ios::trunc);
                    > filesize = filesizer(&infi le);
                    >>
                    > for (i = 0, j = 0; i < filesize; j++, i++) {
                    > if (j >= (7)) { // Reset the key to the begining
                    > j = 0;
                    > outfile.write(b uffer, 8); // Purge buffer to
                    >file
                    > }
                    > infile.seekg(i) ; //sets the get pointed to the
                    >current reference
                    > infile.read(&bu ffer[j],1); //Read the current data at
                    >the get pointer
                    > buffer[j] = buffer[j]^key[j]; //XOR encrypt/decrypt
                    >the current data
                    > }
                    > return;
                    >>
                    >}
                    >>
                    >Of course, you can change your code in others ways. Is it generating
                    >the expected file correctly now?
                    >>
                    >gethostbynam e
                    >>
                    >
                    That worked perfectly to at least allow it to not segmentation fault. It
                    produces encrypted text however the decrypting isn't accurate so I
                    presume that one of my counters isn't correct logic so I'm going to
                    review them and probably have it working in a few minutes. Thank you
                    very much for helping get those pointers correct.
                    >
                    In regard to your other posts the "if (j >= (7))" is just silly as the
                    extra parenthesis are not needed. I think they are a remanent of when I
                    originally intended the program to be able to accept any key length.
                    >
                    Found my issue, the bound j >= 7 should have been j >= 8 so problem is
                    solved and the software does as it was intended...now to write a program
                    that can defeat xor encryption.

                    Comment

                    • Old Wolf

                      #11
                      Re: Simple XOR encryption code issues (segmentation fault)

                      On Mar 12, 4:58 pm, Jerry Coffin <jcof...@taeus. comwrote:
                      class xor : public std::binary_fun ction<char, std::string, char{
                      'xor' is a keyword in C++, so you should choose a different
                      name for your class.


                      Comment

                      • Jerry Coffin

                        #12
                        Re: Simple XOR encryption code issues (segmentation fault)

                        In article <1173746703.602 587.40200@j27g2 000cwj.googlegr oups.com>,
                        oldwolf@inspire .net.nz says...
                        On Mar 12, 4:58 pm, Jerry Coffin <jcof...@taeus. comwrote:
                        class xor : public std::binary_fun ction<char, std::string, char{
                        >
                        'xor' is a keyword in C++, so you should choose a different
                        name for your class.
                        Oops -- good point. Thanks for the correction.

                        --
                        Later,
                        Jerry.

                        The universe is a figment of its own imagination.

                        Comment

                        Working...