Like Tree5Likes

Very simple Encryption problem. My code is not working acording to my logic.. see it.

This is a discussion on Very simple Encryption problem. My code is not working acording to my logic.. see it. within the C Programming forums, part of the General Programming Boards category; Ok, before I startlet me describe what the program that i'm writing needs to do.. 1. The program asks the ...

  1. #1
    Registered User
    Join Date
    Nov 2011
    Posts
    10

    Very simple Encryption problem. My code is not working acording to my logic.. see it.

    Ok, before I startlet me describe what the program that i'm writing needs to do..

    1. The program asks the user to enter a 10-letter word.

    2. Each letter/character entered, is encrypted by changing it to the next adjacent letter of the alphabet.

    eg. if 'a' is entered, it is changed to 'b'
    eg, if the word "dumb" is entered, it is changed to "evnc"


    Now, I've written a code to do this, but it doesn't seem to work well. It is returning the word that i'm inputting same to same
    (i.e, no encryption is taking place.)


    here is my code:


    Code:
             
    # define n 26
    
    int main()
    {
        char a[10];
        char b[n]={'a', 'b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
        int i,j;
        
        printf("Please type your sentence to be Encrypted below: \n\n");
        
        
       
        for(i=0; i<10; i++)
          {   
            scanf("%c", &a[i]);
          }
        
        for(i=0; i<10; i++)
          {
            printf("%c", a[i]);
          }
    
        for(j=0; j<n; j++)
          for (i=0; i<10; i++)
         {           
           if (a[i]!=b[j])              
            {
              j++;            // if there is no match, increment j and continue comparing
            }
          
          else                  //after a match is found,  assign the content at b[j+1] to a[i]
            {                   // then print a[i]
              a[i]=b[j+1];  
              printf("%c", a[i]);
              i++;   
            }
      }
    
       return 0;
    }


    Whats wrong with this code?

    If, this is logically not good, do you know any better way of doing it??

    If so, suggest me so that I can write the program and make it generated the correct output..

    Any help/suggestion is greatly appreciated.
    sagar474 likes this.

  2. #2
    Registered User TheBigH's Avatar
    Join Date
    May 2010
    Location
    Melbourne, Australia
    Posts
    426
    Whoa! You're looping through every letter of the alphabet and painstakingly checking to see if every letter in the message is equal to that letter. "Is the first letter 'a'? Is the second letter 'a'? Is the ... etc etc ... is the first letter 'b'? Is the second letter 'b'"?

    Why would you do this? Why not just loop through the message once and say a[i]++ for each letter? There should be no need to compare anything with an array containing the whole alphabet. There should be no need for nested loops.

    You'll eventually need to deal with capital letters, non-alphabet characters and how to handle 'z', but that's still some way off.
    Code:
    while(!asleep) {
       sheep++;
    }

  3. #3
    Registered User
    Join Date
    Aug 2008
    Location
    Belgrade, Serbia
    Posts
    163
    First of all, a is not big enough to hold that string, you need a buffer that can hold the trailing '\0'. Second, you can use scanf("s", &a), there is no need to get one character at a time. Third, there is no need to construct a table of characters since they all have values one after another in the ASCII table.
    Vanity of vanities, saith the Preacher, vanity of vanities; all is vanity.
    What profit hath a man of all his labour which he taketh under the sun?
    All the rivers run into the sea; yet the sea is not full; unto the place from whence the rivers come, thither they return again.
    For in much wisdom is much grief: and he that increaseth knowledge increaseth sorrow.

  4. #4
    Registered User
    Join Date
    Nov 2011
    Posts
    10
    Quote Originally Posted by TheBigH View Post
    Whoa! You're looping through every letter of the alphabet and painstakingly checking to see if every letter in the message is equal to that letter. "Is the first letter 'a'? Is the second letter 'a'? Is the ... etc etc ... is the first letter 'b'? Is the second letter 'b'"?


    Why would you do this? Why not just loop through the message once and say a[i]++ for each letter? There should be no need to compare anything with an array containing the whole alphabet. There should be no need for nested loops.

    You'll eventually need to deal with capital letters, non-alphabet characters and how to handle 'z', but that's still some way off.

    Ok, is this what you mean??

    Because the program is functioning as I want it..

    Code:
    
    
    int main()
    {
        char a[10];
        
        int i,j;
        
        printf("Please type your sentence to be Encrypted below: \n\n");
        
        
       
        for(i=0; i<10; i++)
          {   
            scanf("%c", &a[i]);
          }
        
        for(i=0; i<10; i++)
          {
            printf("%c", a[i]);
            
          }  
        
        printf("\n\n\n\n");
        printf("The Encrypted text is: ");
        
        for(i=0; i<10; i++)    
        { 
            a[i]++;
            printf("%c", a[i]);
         
         } 
        
        
        printf("\n\n\n\n");
         
    return 0;    
    }
    But, as you said, handling 'z' is another case.. Any idea?

    However, I wish to ignore any spaces and special characters.

  5. #5
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by pprav05 View Post
    Ok, is this what you mean??

    Because the program is functioning as I want it..
    like this....

    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main()
    {
        char uText[100];
        
        int i,j;
        
        printf("Please type your sentence to be Encrypted below: \n\n");
        fgets(uText,99,stdin); 
        printf("%s\n\n",uText);
        printf("The Encrypted text is: \n ");
        
        j = strlen(uText);
    
        for(i=0; i<j; i++)    
           uText[i]++;
    
        printf("%s\n\n", uText);
    
        getchar();
       
        return 0;    
    }

  6. #6
    Registered User TheBigH's Avatar
    Join Date
    May 2010
    Location
    Melbourne, Australia
    Posts
    426
    Quote Originally Posted by pprav05 View Post
    But, as you said, handling 'z' is another case.. Any idea?

    However, I wish to ignore any spaces and special characters.
    Okay, so if your letter is a-y or A-Y you want to do the normal thing.
    If it's z or Z, do something else; I assume you'll want to loop back to the start of the alphabet.
    If it's anything else, do nothing.

    You can quite easily translate the above three sentences into code.
    Code:
    while(!asleep) {
       sheep++;
    }

  7. #7
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Here ya go... decent encryption in 60 lines or less...
    Code:
    // file encrypt and decrypt example
    // encrypt and dectypt using char + key * 2 
    #include <stdio.h>
    #include <stdlib.h>
    
    int main (int argc, char *argv[])
      { char  crypt;  // encryption key
        short fval;   // file values
        FILE  *infile, *outfile;
      
        if(argc < 4)
          { printf("File encryptor/dectyptor...\n");
            printf("Encrypt or decrypt a file based based on a secret method\n\n");
            printf("Usage : \n");
            printf("     crypt <key> <sourcefile> <outputfile>\n\n");
            printf("Key :\n");
            printf("   To encrypt enter a single character as your encryption key\n");
            printf("   To decrypt enter * as the key\n\n");
            printf("Examples :\n");
            printf("     crypt x mywork.txt safework.txt\n");
            printf("     crypt * safework.txt homework.txt\n\n");
            exit(255); }
    
        // open the files
        infile = fopen(argv[2],"rb");
        if (! infile)
          { printf("Unable to open input file\n\n");
            exit(254); }
    
        outfile = fopen(argv[3],"wb");
        if (! outfile)
          { printf("Unable to open output file\n\n");
            exit(253); }
    
        // active encryptor     
        if ((argv[1][0] == '*'))
          { printf("Decrypting...\n\n");
            // first value in the file is the key
            if ( fread(&crypt, sizeof(char), 1, infile) )
              { crypt = ~crypt;                
                while( fread(&fval ,sizeof(short), 1, infile) )
                  fputc( (fval / 2) - crypt, outfile );  } }
        else
          { printf("Encrypting...\n\n");
            // set key as first value in file}    
            crypt = ~argv[1][0];
            fwrite(&crypt, sizeof(char), 1, outfile);
            while( (fval = fgetc(infile)) > 0 )
              { fval = (fval + argv[1][0]) * 2;
              fwrite(&fval,sizeof(short),1,outfile); } }
            
        fclose(infile);
        fclose(outfile);
    
        printf("Done...\n\n\n");    
        return 0; }
    Encrypting it's own source code...

    PHP Code:
       NTZL L^Hftbj D^J JLHftbj LrD\bZL     L^Hftbj D^J JLHjtbj lhT^P HRDf   XLt        T^HZlJL  hjJT` R    T^HZlJL  hjJZTF R     T^j \DT^  T^j DfPH  HRDf  DfPn8<     x T^j Hftbj      L^HftbjT`^ XLt      T^j NnDZ       NTZL nDZlLh        T^NTZL   `ljNTZL           TN DfPH             x bfT^jN  TZL L^Hftbj`f JLHjtbj`f   :^             bfT^jN   ^Hftbj `f JLHftbj D NTZL FDhLJ FDhLJ `^ D hLHfLj \LjR`J:^:^             bfT^jN  ,hDPL   :^             bfT^jN       Hftbj  XLt   h`lfHLNTZL   `ljbljNTZL :^:^             bfT^jN  Lt  :^             bfT^jN     *` L^Hftbj L^jLf D hT^PZL HRDfDHjLf Dh t`lf L^HftbjT`^ XLt:^             bfT^jN     *` JLHftbj L^jLf   Dh jRL XLt:^:^             bfT^jN  rD\bZLh  :^             bfT^jN       Hftbj r \tp`fX jrj hDNLp`fX jrj:^             bfT^jN       Hftbj   hDNLp`fX jrj R`\Lp`fX jrj:^:^             LrTj       |           `bL^ jRL NTZLh      T^NTZL   N`bL^ DfPn8 <  f         TN    T^NTZL         x bfT^jN  ,^DFZL j` `bL^ T^blj NTZL:^:^             LrTj       |        `ljNTZL   N`bL^ DfPn8 <  p         TN    `ljNTZL         x bfT^jN  ,^DFZL j``bL^ `ljblj NTZL:^:^             LrTj       |           DHjTnL L^Hftbj`f           TN   DfPn8 <<                 x bfT^jN  
    LHftbjT
    ^P   :^:^                NTfhj nDZlL T^ jRL NTZL Th jRL XLt          TN   NhHD^N T^NTZL   J   Hftbj                  pRTZL NhHD^N T^NTZL   J   NnDZ                    NbljH  NnDZ      Hftbj `ljNTZL    |      LZhL        x bfT^jN   ^HftbjT^P   :^:^                hLj XLt Dh NTfhj nDZlL T^ NTZL|              NbfT^jN `ljNTZL   J   DfPn8 <<            pRTZL   NnDZ   NPLjH T^NTZL                    NbfT^jN `ljNTZL   J     NnDZ   DfPn8 <8 <        |                NHZ`hL T^NTZL        NHZ`hL `ljNTZL          bfT^jN  
    `^L   :^:^:^             fLjlf^    |      

  8. #8
    Registered User
    Join Date
    Nov 2011
    Posts
    10

    Thats great

    Quote Originally Posted by CommonTater View Post
    like this....

    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main()
    {
        char uText[100];
        
        int i,j;
        
        printf("Please type your sentence to be Encrypted below: \n\n");
        fgets(uText,99,stdin); 
        printf("%s\n\n",uText);
        printf("The Encrypted text is: \n ");
        
        j = strlen(uText);
    
        for(i=0; i<j; i++)    
           uText[i]++;
    
        printf("%s\n\n", uText);
    
        getchar();
       
        return 0;    
    }

    Wow, thats, great though I'm feeling a bit.... you wrote the code.. But well, Big thanks... I'm working with this method along with other method described here.. Thanks everybody..

  9. #9
    Registered User
    Join Date
    Nov 2011
    Posts
    10

    OMG.. whats that..

    Quote Originally Posted by CommonTater View Post
    Here ya go... decent encryption in 60 lines or less...
    Code:
    // file encrypt and decrypt example
    // encrypt and dectypt using char + key * 2 
    #include <stdio.h>
    #include <stdlib.h>
    
    int main (int argc, char *argv[])
      { char  crypt;  // encryption key
        short fval;   // file values
        FILE  *infile, *outfile;
      
        if(argc < 4)
          { printf("File encryptor/dectyptor...\n");
            printf("Encrypt or decrypt a file based based on a secret method\n\n");
            printf("Usage : \n");
            printf("     crypt <key> <sourcefile> <outputfile>\n\n");
            printf("Key :\n");
            printf("   To encrypt enter a single character as your encryption key\n");
            printf("   To decrypt enter * as the key\n\n");
            printf("Examples :\n");
            printf("     crypt x mywork.txt safework.txt\n");
            printf("     crypt * safework.txt homework.txt\n\n");
            exit(255); }
    
        // open the files
        infile = fopen(argv[2],"rb");
        if (! infile)
          { printf("Unable to open input file\n\n");
            exit(254); }
    
        outfile = fopen(argv[3],"wb");
        if (! outfile)
          { printf("Unable to open output file\n\n");
            exit(253); }
    
        // active encryptor     
        if ((argv[1][0] == '*'))
          { printf("Decrypting...\n\n");
            // first value in the file is the key
            if ( fread(&crypt, sizeof(char), 1, infile) )
              { crypt = ~crypt;                
                while( fread(&fval ,sizeof(short), 1, infile) )
                  fputc( (fval / 2) - crypt, outfile );  } }
        else
          { printf("Encrypting...\n\n");
            // set key as first value in file}    
            crypt = ~argv[1][0];
            fwrite(&crypt, sizeof(char), 1, outfile);
            while( (fval = fgetc(infile)) > 0 )
              { fval = (fval + argv[1][0]) * 2;
              fwrite(&fval,sizeof(short),1,outfile); } }
            
        fclose(infile);
        fclose(outfile);
    
        printf("Done...\n\n\n");    
        return 0; }
    Encrypting it's own source code...

    PHP Code:
       NTZL L^Hftbj D^J JLHftbj LrD\bZL     L^Hftbj D^J JLHjtbj lhT^P HRDf   XLt        T^HZlJL  hjJT` R    T^HZlJL  hjJZTF R     T^j \DT^  T^j DfPH  HRDf  DfPn8<     x T^j Hftbj      L^HftbjT`^ XLt      T^j NnDZ       NTZL nDZlLh        T^NTZL   `ljNTZL           TN DfPH             x bfT^jN  TZL L^Hftbj`f JLHjtbj`f   :^             bfT^jN  ^Hftbj `f JLHftbj D NTZL FDhLJ FDhLJ `^ D hLHfLj \LjR`J:^:^             bfT^jN  ,hDPL   :^             bfT^jN       Hftbj  XLt   h`lfHLNTZL   `ljbljNTZL :^:^             bfT^jN  Lt  :^             bfT^jN     *` L^Hftbj L^jLf D hT^PZL HRDfDHjLf Dh t`lf L^HftbjT`^ XLt:^             bfT^jN     *` JLHftbj L^jLf   Dh jRL XLt:^:^             bfT^jN  rD\bZLh  :^             bfT^jN       Hftbj r \tp`fX jrj hDNLp`fX jrj:^             bfT^jN       Hftbj   hDNLp`fX jrj R`\Lp`fX jrj:^:^             LrTj       |           `bL^ jRL NTZLh      T^NTZL   N`bL^ DfPn8 <  f         TN    T^NTZL         x bfT^jN  ,^DFZL j` `bL^ T^blj NTZL:^:^             LrTj       |        `ljNTZL   N`bL^ DfPn8 <  p         TN    `ljNTZL         x bfT^jN  ,^DFZL j` `bL^ `ljblj NTZL:^:^             LrTj       |           DHjTnL L^Hftbj`f           TN   DfPn8 <<                 x bfT^jN  
    LHftbjT
    ^P   :^:^                NTfhj nDZlL T^ jRL NTZL Th jRL XLt          TN   NhHD^N T^NTZL   J   Hftbj                  pRTZL NhHD^N T^NTZL   J   NnDZ                    NbljH  NnDZ      Hftbj `ljNTZL    |      LZhL        x bfT^jN  ^HftbjT^P   :^:^                hLj XLt Dh NTfhj nDZlL T^ NTZL|              NbfT^jN `ljNTZL   J   DfPn8 <<            pRTZL   NnDZ   NPLjH T^NTZL                    NbfT^jN `ljNTZL   J     NnDZ   DfPn8 <8 <        |                NHZ`hL T^NTZL        NHZ`hL `ljNTZL          bfT^jN  
    `^L   :^:^:^             fLjlf^    |      

    I'm getting mad.. I better stick to your previous code.. Its much easier..
    hauzer likes this.

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,588
    Quote Originally Posted by pprav05
    I'm getting mad.. I better stick to your previous code.. Its much easier..
    Nah, you can just wrap the encryption and decryption parts of what CommonTater wrote into functions, then it will be just as easy to reuse. The output might look scary, but then ciphertext does not have to be human readable, although you could pass it through some encoding method (e.g., base64 encoding).

    That said, take the "decent encryption" with a pinch of salt: in reality, it is weak, but you probably were not going for strong encryption anyway.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  11. #11
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by laserlight View Post
    That said, take the "decent encryption" with a pinch of salt
    "Decent encryption" means that it did the job well enough that Joe Average can't read the file.
    In fact merely owning the program allows anyone to decrypt the text, so "strong" or even "moderate" encryption would be a false claim here.

    I also didn't intend for the OP or his friend to actually take and use that code as homework... It's merely an example. In fact, if they did hand that in, it's very likely they'd get flunked for cheating as I suspect it's rather beyond their skill levels.... In any case I was merely showing them what can be done with relatively little code... all the good stuff happens from line 35 to line 50.

  12. #12
    Registered User sagar474's Avatar
    Join Date
    Jun 2011
    Location
    Kakinada
    Posts
    56
    I cant understand your logic. but I'm sure the logic is more simple thane that you think.

    this program will work as per your description.

    Code:
    #include<stdio.h>
    int main()
    {
    
        char a[100];
        int i=0;
    printf("Please type your sentence to be Encrypted below: \n");
    gets(a);
    
    while(a[i]!='\0')
    {
    if((a[i]<=57 && a[i]>=48)||(a[i]<=90  && a[i]>=65 )|| (a[i]<=122 && a[i]>=97))
    {
    if(a[i]=='z')a[i]='a';
    else if(a[i]=='Z')a[i]='A';
    else if(a[i]=='9')a[i]='0';
    else ++a[i];
    }
    ++i;
    }
    
    printf("The Encrypted text is: ");
    printf("%s",a);
        return 0;
    }
    refer the ascii table. identify the printable chars.
    Last edited by sagar474; 11-08-2011 at 04:33 PM.
    pprav05 likes this.

  13. #13
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,588
    Quote Originally Posted by sagar474
    this program will work as per your description.
    I suggest that you:
    • Indent your code properly.
    • Avoid the use of gets.
    • Avoid magic numbers (perhaps by using isdigit, isupper and islower instead).
    TheBigH likes this.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  14. #14
    Registered User sagar474's Avatar
    Join Date
    Jun 2011
    Location
    Kakinada
    Posts
    56
    Avoid the use of gets.
    yes compiler warned me but i ignored. when you pointed out i red about it. yes it is dangerous. instead can i replace it with fgets ?

    Avoid magic numbers (perhaps by using isdigit, isupper and islower instead)
    why should we call a function every time even tho the logic is very simple?

  15. #15
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,451
    Quote Originally Posted by sagar474 View Post
    yes compiler warned me but i ignored. when you pointed out i red about it. yes it is dangerous. instead can i replace it with fgets ?
    Ignoring compiler warnings is like saying you're smarter than the compiler, which you probably aren't (not that I think you're dumb, just the compiler knows C better than you). Those warnings are there to notify you of questionable code, so you should pay careful attention to them and resolve all of your warnings. And yes, you can replace it with a call to fgets:
    Code:
    char buf[100];
    fgets(buf, sizeof(buf), stdin);
    Quote Originally Posted by sagar474 View Post
    why should we call a function every time even tho the logic is very simple?
    A great number of reasons:
    • The logic itself is simple, a few < or >= checks, but it's intent is not clear, especially because you use magic numbers instead of 'A' or 'z'. Functions have clear names that make it obvious what they're trying to do. Clear, readable code should be paramount in your programming endeavors.
    • Your magic numbers are specific to ASCII. If a system is using something like EBCDIC, your code will break, while the functions will not.
    • Using range checks is not a good idea. Not all code systems store the letters sequentially, like EBCDIC, for example.
    • Those functions are defined by the C standard, and every conforming implementation will support them. A smart compiler may inline that function call anyway, and it will end up being as fast as your code, but easier to read.
    • The overhead of the function call is very small, so the cost incurred is not likely to be an issue. Don't optimize prematurely.
    Somebody else can probably come up with more reasons, but hopefully that is enough to convince you.
    jeremy duncan likes this.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Simple Logic problem
    By will of fortune in forum C Programming
    Replies: 4
    Last Post: 03-06-2010, 01:25 PM
  2. problem with previously working internet code
    By abachler in forum Windows Programming
    Replies: 11
    Last Post: 04-10-2009, 04:11 AM
  3. RFC - Simple Encryption
    By Nor in forum C++ Programming
    Replies: 11
    Last Post: 02-16-2009, 03:59 PM
  4. Bitswitching Encryption not working
    By Geo-Fry in forum C++ Programming
    Replies: 4
    Last Post: 06-03-2003, 04:45 PM
  5. Program logic not working..
    By ronkane in forum C++ Programming
    Replies: 2
    Last Post: 01-22-2002, 07:31 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21