Thread: Encryption program using bitwise operators fails during the encryption stage.

  1. #1
    Registered User
    Join Date
    Nov 2011
    Location
    Buea, Cameroon
    Posts
    197

    Encryption program using bitwise operators fails during the encryption stage.

    Hey guys i am writing an encryption program that uses bitshifts to encrypt characters in a message and then receives a key from the user to perform an opposite shift to restore the original message.I divided the program into three functions: read_msg(), encrypt(), decrypt(). but it fails at the encryption part. i donot want to use another array there i just want to perform the bitshift on the same array and store the values.
    Code:
    /****************************************************************************************************************************
     * FileName: crypto.c                                                                                                       *
     * Developer: Nyah Check, INK Corp.                                                                                         *
     * Usage   : This program encrypts data following a key entered by the user. and prints the encrypted message.              *
     *                                                                                                                          *
     * Copyright: The code for this program is free to be distributed                                                           *
     *            and licenced freely following the opensource idea                                                             *
     *            no money should be demanded for its usage and the                                                             *
     *            user is responsible for what he/she does with it.                                                             *
     * INK Corporation, 2012..                                                                                                  *
     ****************************************************************************************************************************/
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define MAX 140
    #define getchar()     getc(stdin)
    
    int read_line(unsigned char s[]);
    int encrypt(unsigned char s[], int n);
    int decrypt(unsigned char s[], int key);
    int i, key;
    
    
    /**************************************************************************************************************************************
     *Main: This  calls three functions read_line(), encrypt(), and decrypt() for the decryption sequence given by the key.               *
     *                                                                                                                                    *
     *                                                                                                                                    *
     **************************************************************************************************************************************/
    
    int  main()
    {
        unsigned char msg[MAX + 1];
    
        printf("\nThanks for using our encryption program that encrypts text messages.Takes a maximum of 140 characters. ");
        printf("\nDecryption is done using an input key. If you wish to quit the program, ENTER '&'(ampersand)...\n");
        printf("\nINK Corporation, 2012.\n\n");
    
            printf("\nEnter the plain text: ");
            read_line(msg);
    
            printf("\nEncrpted text: ");
            encrypt(msg, i);
    
            printf("Enter decryption code: ");
            key = getc(stdin);
    
            switch(key)
            {
                case ' ': case '\n': case '\0': printf("\nNo key entered. Try again!!!");
                                                break;
    
                default:                        decrypt (msg, key);
                                                break;
            }
        return 0;
    }
    
    /**************************************************************************************************************************************
     *Function Name: read_line():                                                                                                         *
     *Function:      This function reads input from the keyboard and then passes them to the  encrypting function which then encrypts the *
     *                message.
     *Precondition:  (plaintext).                                                                                                         *
     *Postcondition:    Encrypted message.                                                                                                *
     **************************************************************************************************************************************/
    
     int read_line( unsigned char s[])
    {
        int ch;
    
        while ( (ch = getchar()) != '\n')
        {
            if ( ch == '&')
            {
                printf("\nThanks for trusting the services of INK Corporation");
                printf(". We would like to receive your comments and feedbacks to better our services");
                printf("\nINK Corporation, PALO ALTO CA. 2012.");
                exit(EXIT_FAILURE);
            }
    
            else if ( i < MAX)
                s[i++] = ch;
    
        }
    
         s[i] = '\0';
    
         if (i < 0)
         {
            printf("A matching failure occured while writing message.");
            exit(EXIT_FAILURE);
         }
    
         return i;
    }
    
    /******************************************************************************
     *encrypt(): This function encrypts a message depending on a predetermined key*
     *           then prints the encrypted message.                               *
     ******************************************************************************/
    int encrypt(unsigned char s[], int i)
    {
        int t = 0;
        unsigned char nstr[i];
    
        while ( s[t] != '\0')
        {
    
            if ( t < i)
            nstr[t++]  = 20 << s[t];
        }
       nstr[t] = '\0';
       if (nstr == NULL)
       {
            printf("\nAn matching failure occured while encrypting message.");
            exit(EXIT_FAILURE);
       }
    
    
        printf("%s\n",nstr);
    
        return t;
    }
    
    /*********************************************************************************
     *decrypt(): This function decrypts the message entered by the user depending on *
     *           the decryption key entered by the user.                             *
     *********************************************************************************/
    
     int decrypt( unsigned char s[], int key)
     {
    
         int res, t = 0;
    
         while ( s[t] != '\0')
         {
              if ( t < i)
                s[t++] = key >> s[t];
         }
         s[t] = '\0';
    
         if (s == NULL)
         {
            printf("\nAn error occured while decrypting message.");
            exit(EXIT_FAILURE);
        }
    
         printf("\nDecrypted message: %s", s);
    
         printf("\nWas the Decryption Succesful (y, n)? ");
    
         if ((res = getc(stdin)) == 'y' || res ==  'Y')
             printf("\nCongratulations on decrypting your messages.");
    
         else
            printf("\nTry better next time.. Courage!!!!");
    
         return t;
     }

  2. #2
    Registered User
    Join Date
    Mar 2011
    Posts
    546
    if (nstr == NULL) will never be true. 'nstr' by itself will give you the address of the variable, which will never be 0. you have that same issue elsewhere. what are you testing for?

  3. #3
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    First things first, you have some undefined behavior. Technically this must be cleared up before we can say for sure what your problem is. I get the following when I compile your code:
    Code:
    $ make crypt
    gcc -Wall -g -std=c99  -lm -lpthread -lcurses -lefence  crypt.c   -o crypt
    crypt.c: In function ‘encrypt’:
    crypt.c:111: warning: operation on ‘t’ may be undefined
    crypt.c: In function ‘decrypt’:
    crypt.c:139: warning: operation on ‘t’ may be undefined
    Read this: http://c-faq.com/expr/evalorder1.html. Then move the t++ to it's own statement after those lines (make sure you add brackets to the if statement above and keep the t++ in that if statement).

    Also, don't use global variables. Read this: Global Variables Are Bad. Declare them in the appropriate function and pass them around as needed.

    How exactly does it "fail at the encryption part". Be specific. No output? Garbled output or junk characters? Sensible but incorrect output?

    What do you think happens when you shift an 8-bit character 20 positions to the left? You shift all the bits off the left and are left with a zero for each char in nstr. There's nothing for the printf to show.

  4. #4
    Registered User
    Join Date
    Nov 2011
    Location
    Buea, Cameroon
    Posts
    197
    Code:
    //This is a modified version
    int encrypt(unsigned char s[], int i)
    {
        int t = 0;
        unsigned char nstr[i];
    
        while ( s[t] != '\0')
        {
    
            if ( t < i)
            nstr[t]  = 20 << s[t];
            t++
        }
       nstr[t] = '\0';
       if (sizeof(nstr) == 0)
       {
            printf("\nAn matching failure occured while encrypting message.");
            exit(EXIT_FAILURE);
       }
    
    
        printf("%s\n",nstr);
    
        return t;
    }
    
    
    
    
    let see if this is better

  5. #5
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    It's a little better, but not much. You completely ignored the last two lines of my post. Reread them, you still have serious errors.

  6. #6
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,834
    nstr[t] = 20 << s[t];
    That's not going to work. You can't shift 20 left for 90 bits (Capital 'Z' is 90) and expect to retain the result especially when assigning to an 8 bit char.

  7. #7
    Registered User
    Join Date
    Dec 2011
    Posts
    795
    Code:
     *Function Name: read_line():                                                                                                         *
     *Function:      This function reads input from the keyboard and then passes them to the  encrypting function which then encrypts the *
     *                message.
     *Precondition:  (plaintext).                                                                                                         *
     *Postcondition:    Encrypted message.
    If you're going to add useless function comment headers, at least make them correct. It doesn't pass the message to anything. Also, why use all of that overhead? Just use fgets() for the sizeof(s), and then use strchr() to find the ampersand.

    Code:
                printf("\nINK Corporation, PALO ALTO CA. 2012.");
    You live in cameroon. Seriously stop ._.

    As nonoob said, your encryption function won't work. Shoving random bitwise operators won't make for a secure and reversible algorithm. I would recommend you reading this link > Tutorials - Bitwise Operators and Bit Manipulations in C and C++ - Cprogramming.com before continuing.

    Code:
         printf("\nWas the Decryption Succesful (y, n)? ");
     
         if ((res = getc(stdin)) == 'y' || res ==  'Y')
             printf("\nCongratulations on decrypting your messages.");
     
         else
            printf("\nTry better next time.. Courage!!!!");
    What does this do? Why don't you just pass around a struct/array that has the strings in it, and compare?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Encryption Program (help me please)
    By Arkanos in forum Windows Programming
    Replies: 7
    Last Post: 10-30-2005, 08:01 PM
  2. Encryption program
    By zeiffelz in forum C Programming
    Replies: 1
    Last Post: 06-15-2005, 03:39 AM
  3. Hi, encryption program
    By Blue_turnip in forum C++ Programming
    Replies: 28
    Last Post: 01-05-2005, 09:41 AM
  4. Help with my encryption program
    By quiksilver9531 in forum C++ Programming
    Replies: 9
    Last Post: 02-18-2002, 04:26 AM