Thread: What's wrong with my code (encryption-decryption error)?

  1. #1
    Registered User
    Join Date
    May 2016
    Posts
    11

    Question What's wrong with my code (encryption-decryption error)?

    The problem is when decrypting a ciphertext already encrypted with my program it gives a word with a letter different than the original one ;so word->encrypted ... then encrypted->decrypted gives decrypted!=word,and even on paper the ciphertext should be different than the one i'm getting. And an other thing:i tried using
    Code:
    do{...}while (strlen(...,...)!=0)
    to have the key length equal to the password length but it isn't working and tried comparing sizeof also not working. How should i compare the length of the key with the word?

    Here is my code using xor :

    Code:
    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    #define clear_buffer while(getchar()!='\n');
    
    char* encrypt(char texte[],char cle[]){
        char*encrypted;
        int i=0;
    
        while(texte[i]!='\0'&& cle[i]!='\0'){
            if(texte[i]>='A'&& texte[i]<='Z')
             encrypted[i]=((texte[i]-'A')^(cle[i]-'A'))%26+'A';
        elseif(texte[i]>='a'&& texte[i]<='z')
             encrypted[i]=((texte[i]-'a')^(cle[i]-'a'))%26+'a';
        i++;
        }
        encrypted[i+1]='\0';
        return encrypted;   
    
        }
    char* decrypt(char encrypted[],char cle[]){
        char*decrypted;
        int i=0;
    
        while(encrypted[i]!='\0'&& cle[i]!='\0'){
             if(encrypted[i]>='A'&& encrypted[i]<='Z')
              decrypted[i]=((encrypted[i]-'A')^(cle[i]-'A'))%26+'A';
         elseif(encrypted[i]>='a'&& encrypted[i]<='z')
              decrypted[i]=((encrypted[i]-'a')^(cle[i]-'a'))%26+'a';
         i++;
        }
        decrypted[i+1]=0;
        return decrypted;
    
    }
    int main()
    {
        char reponse,texte[100],cle[100],encrypted[100];
        int i=0;
    
        do{
        printf("Voulez vous crypter ou decrypter un texte?(Ecrire C pour crypter et D pour decrypter)\n");
        scanf("%c",&reponse);
        }while(reponse!='C'&& reponse!='D'&& reponse!='c'&& reponse!='d');//controle pour obliger l'utilisateur à donner c ou d
    if(reponse=='C'||reponse=='c'){
        clear_buffer;//vider le buffer apres le scanf de la reponse
                    //do{
            printf("Donner un texte a crypter\n");
            fgets(texte,100,stdin);
            while(texte[i]!=0)
        i++;
            if(i>0&& texte[i-1]!='\n')
        clear_buffer;
            printf("Donner une cle de meme taille\n");
            fgets(cle,100,stdin);
                //}while(sizeof texte!=sizeof cle);
            i=0;
            while(cle[i]!=0)
        i++;
            if(i>0&& cle[i-1]!='\n')
        clear_buffer;
            printf("Le texte crypte est:%s\n",encrypt(texte,cle));
        }else{
        clear_buffer;//vider le buffer apres le scanf de la reponse
            //  do{
            printf("Donner un texte (deja crypte) à decrypter\n");
            fgets(encrypted,100,stdin); 
            i=0;
            while(encrypted[i]!=0)
        i++;
            if(i>0&& encrypted[i-1]!='\n')
        clear_buffer;
            printf("Donner la cle (deja utilisee pour crypter\n");
            fgets(cle,100,stdin);
            i=0;
            while(cle[i]!=0)
        i++;
            if(i>0&& cle[i-1]!='\n')
        clear_buffer;
            //}while(sizeof encrypted!=sizeof cle);
            printf("Le texte decrypte est:%s\n",decrypt(encrypted,cle));
        }
        system("pause");
        return 0;
    }
    
    Last edited by techlover1; 05-16-2016 at 12:39 AM.

  2. #2
    Registered User
    Join Date
    May 2016
    Posts
    11
    Here is an example of the output problem:
    What's wrong with my code (encryption-decryption error)?-ex2out1-jpgWhat's wrong with my code (encryption-decryption error)?-ex2out2-jpg

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    1. Your indentation is poor.
    Indent style - Wikipedia, the free encyclopedia

    Compare with
    Code:
    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    #define clear_buffer while(getchar()!='\n');
    
    char *encrypt(char texte[], char cle[])
    {
      char *encrypted;
      int i = 0;
    
      while (texte[i] != '\0' && cle[i] != '\0') {
        if (texte[i] >= 'A' && texte[i] <= 'Z')
          encrypted[i] = ((texte[i] - 'A') ^ (cle[i] - 'A')) % 26 + 'A';
        else if(texte[i] >= 'a' && texte[i] <= 'z')
            encrypted[i] = ((texte[i] - 'a') ^ (cle[i] - 'a')) % 26 + 'a';
        i++;
      }
      encrypted[i + 1] = '\0';
      return encrypted;
    
    }
    
    char *decrypt(char encrypted[], char cle[])
    {
      char *decrypted;
      int i = 0;
    
      while (encrypted[i] != '\0' && cle[i] != '\0') {
        if (encrypted[i] >= 'A' && encrypted[i] <= 'Z')
          decrypted[i] = ((encrypted[i] - 'A') ^ (cle[i] - 'A')) % 26 + 'A';
        else if(encrypted[i] >= 'a' && encrypted[i] <= 'z')
            decrypted[i] = ((encrypted[i] - 'a') ^ (cle[i] - 'a')) % 26 + 'a';
        i++;
      }
      decrypted[i + 1] = 0;
      return decrypted;
    
    }
    
    int main()
    {
      char reponse, texte[100], cle[100], encrypted[100];
      int i = 0;
    
      do {
        printf("Voulez vous crypter ou decrypter un texte?(Ecrire C pour crypter et D pour decrypter)\n");
        scanf("%c", &reponse);
      } while (reponse != 'C' && reponse != 'D' && reponse != 'c' && reponse != 'd'); //controle pour obliger l'utilisateur à donner c ou d
      if (reponse == 'C' || reponse == 'c') {
        clear_buffer;               //vider le buffer apres le scanf de la reponse
        //do{
        printf("Donner un texte a crypter\n");
        fgets(texte, 100, stdin);
        while (texte[i] != 0)
          i++;
        if (i > 0 && texte[i - 1] != '\n')
          clear_buffer;
        printf("Donner une cle de meme taille\n");
        fgets(cle, 100, stdin);
        //}while(sizeof texte!=sizeof cle);
        i = 0;
        while (cle[i] != 0)
          i++;
        if (i > 0 && cle[i - 1] != '\n')
          clear_buffer;
        printf("Le texte crypte est:%s\n", encrypt(texte, cle));
      } else {
        clear_buffer;               //vider le buffer apres le scanf de la reponse
        //  do{
        printf("Donner un texte (deja crypte) à decrypter\n");
        fgets(encrypted, 100, stdin);
        i = 0;
        while (encrypted[i] != 0)
          i++;
        if (i > 0 && encrypted[i - 1] != '\n')
          clear_buffer;
        printf("Donner la cle (deja utilisee pour crypter\n");
        fgets(cle, 100, stdin);
        i = 0;
        while (cle[i] != 0)
          i++;
        if (i > 0 && cle[i - 1] != '\n')
          clear_buffer;
        //}while(sizeof encrypted!=sizeof cle);
        printf("Le texte decrypte est:%s\n", decrypt(encrypted, cle));
      }
      //system("pause");
      return 0;
    }
    2. Compile with lots of warnings enabled.
    Code:
    $ gcc -g -Wall -Wextra -O2 foo.c
    foo.c: In function ‘main’:
    foo.c:47:10: warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result [-Wunused-result]
    foo.c:53:10: warning: ignoring return value of ‘fgets’, declared with attribute warn_unused_result [-Wunused-result]
    foo.c:59:10: warning: ignoring return value of ‘fgets’, declared with attribute warn_unused_result [-Wunused-result]
    foo.c:71:10: warning: ignoring return value of ‘fgets’, declared with attribute warn_unused_result [-Wunused-result]
    foo.c:78:10: warning: ignoring return value of ‘fgets’, declared with attribute warn_unused_result [-Wunused-result]
    foo.c: In function ‘encrypt’:
    foo.c:18:12: warning: ‘encrypted’ is used uninitialized in this function [-Wuninitialized]
    foo.c: In function ‘decrypt’:
    foo.c:35:12: warning: ‘decrypted’ is used uninitialized in this function [-Wuninitialized]
    The last two are critical - neither of your result pointers are pointing to valid memory.

    On my machine, it just crashes as soon as it attempts to use the invalid pointer.
    Code:
    $ valgrind ./a.out
    ==2505== Memcheck, a memory error detector
    ==2505== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al.
    ==2505== Using Valgrind-3.6.1-Debian and LibVEX; rerun with -h for copyright info
    ==2505== Command: ./a.out
    ==2505== 
    Voulez vous crypter ou decrypter un texte?(Ecrire C pour crypter et D pour decrypter)
    c
    Donner un texte a crypter
    hello
    Donner une cle de meme taille
    hello
    ==2505== Invalid write of size 1
    ==2505==    at 0x400AA4: encrypt (foo.c:15)
    ==2505==    by 0x4008C5: main (foo.c:66)
    ==2505==  Address 0x0 is not stack'd, malloc'd or (recently) free'd
    ==2505== 
    ==2505== 
    ==2505== Process terminating with default action of signal 11 (SIGSEGV)
    ==2505==  Access not within mapped region at address 0x0
    ==2505==    at 0x400AA4: encrypt (foo.c:15)
    ==2505==    by 0x4008C5: main (foo.c:66)
    ==2505==  If you believe this happened as a result of a stack
    ==2505==  overflow in your program's main thread (unlikely but
    ==2505==  possible), you can try to increase the size of the
    ==2505==  main thread stack using the --main-stacksize= flag.
    ==2505==  The main thread stack size used in this run was 8388608.
    ==2505== 
    ==2505== HEAP SUMMARY:
    ==2505==     in use at exit: 0 bytes in 0 blocks
    ==2505==   total heap usage: 0 allocs, 0 frees, 0 bytes allocated
    ==2505== 
    ==2505== All heap blocks were freed -- no leaks are possible
    ==2505== 
    ==2505== For counts of detected and suppressed errors, rerun with: -v
    ==2505== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 4 from 4)
    Segmentation fault
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Registered User
    Join Date
    May 2016
    Posts
    11
    Quote Originally Posted by Salem View Post
    1. Your indentation is poor.
    Indent style - Wikipedia, the free encyclopedia

    Compare with
    Code:
    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    #define clear_buffer while(getchar()!='\n');
    
    char *encrypt(char texte[], char cle[])
    {
      char *encrypted;
      int i = 0;
    
      while (texte[i] != '\0' && cle[i] != '\0') {
        if (texte[i] >= 'A' && texte[i] <= 'Z')
          encrypted[i] = ((texte[i] - 'A') ^ (cle[i] - 'A')) % 26 + 'A';
        else if(texte[i] >= 'a' && texte[i] <= 'z')
            encrypted[i] = ((texte[i] - 'a') ^ (cle[i] - 'a')) % 26 + 'a';
        i++;
      }
      encrypted[i + 1] = '\0';
      return encrypted;
    
    }
    
    char *decrypt(char encrypted[], char cle[])
    {
      char *decrypted;
      int i = 0;
    
      while (encrypted[i] != '\0' && cle[i] != '\0') {
        if (encrypted[i] >= 'A' && encrypted[i] <= 'Z')
          decrypted[i] = ((encrypted[i] - 'A') ^ (cle[i] - 'A')) % 26 + 'A';
        else if(encrypted[i] >= 'a' && encrypted[i] <= 'z')
            decrypted[i] = ((encrypted[i] - 'a') ^ (cle[i] - 'a')) % 26 + 'a';
        i++;
      }
      decrypted[i + 1] = 0;
      return decrypted;
    
    }
    
    int main()
    {
      char reponse, texte[100], cle[100], encrypted[100];
      int i = 0;
    
      do {
        printf("Voulez vous crypter ou decrypter un texte?(Ecrire C pour crypter et D pour decrypter)\n");
        scanf("%c", &reponse);
      } while (reponse != 'C' && reponse != 'D' && reponse != 'c' && reponse != 'd'); //controle pour obliger l'utilisateur à donner c ou d
      if (reponse == 'C' || reponse == 'c') {
        clear_buffer;               //vider le buffer apres le scanf de la reponse
        //do{
        printf("Donner un texte a crypter\n");
        fgets(texte, 100, stdin);
        while (texte[i] != 0)
          i++;
        if (i > 0 && texte[i - 1] != '\n')
          clear_buffer;
        printf("Donner une cle de meme taille\n");
        fgets(cle, 100, stdin);
        //}while(sizeof texte!=sizeof cle);
        i = 0;
        while (cle[i] != 0)
          i++;
        if (i > 0 && cle[i - 1] != '\n')
          clear_buffer;
        printf("Le texte crypte est:%s\n", encrypt(texte, cle));
      } else {
        clear_buffer;               //vider le buffer apres le scanf de la reponse
        //  do{
        printf("Donner un texte (deja crypte) à decrypter\n");
        fgets(encrypted, 100, stdin);
        i = 0;
        while (encrypted[i] != 0)
          i++;
        if (i > 0 && encrypted[i - 1] != '\n')
          clear_buffer;
        printf("Donner la cle (deja utilisee pour crypter\n");
        fgets(cle, 100, stdin);
        i = 0;
        while (cle[i] != 0)
          i++;
        if (i > 0 && cle[i - 1] != '\n')
          clear_buffer;
        //}while(sizeof encrypted!=sizeof cle);
        printf("Le texte decrypte est:%s\n", decrypt(encrypted, cle));
      }
      //system("pause");
      return 0;
    }
    2. Compile with lots of warnings enabled.
    Code:
    $ gcc -g -Wall -Wextra -O2 foo.c
    foo.c: In function ‘main’:
    foo.c:47:10: warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result [-Wunused-result]
    foo.c:53:10: warning: ignoring return value of ‘fgets’, declared with attribute warn_unused_result [-Wunused-result]
    foo.c:59:10: warning: ignoring return value of ‘fgets’, declared with attribute warn_unused_result [-Wunused-result]
    foo.c:71:10: warning: ignoring return value of ‘fgets’, declared with attribute warn_unused_result [-Wunused-result]
    foo.c:78:10: warning: ignoring return value of ‘fgets’, declared with attribute warn_unused_result [-Wunused-result]
    foo.c: In function ‘encrypt’:
    foo.c:18:12: warning: ‘encrypted’ is used uninitialized in this function [-Wuninitialized]
    foo.c: In function ‘decrypt’:
    foo.c:35:12: warning: ‘decrypted’ is used uninitialized in this function [-Wuninitialized]
    The last two are critical - neither of your result pointers are pointing to valid memory.

    On my machine, it just crashes as soon as it attempts to use the invalid pointer.
    Code:
    $ valgrind ./a.out
    ==2505== Memcheck, a memory error detector
    ==2505== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al.
    ==2505== Using Valgrind-3.6.1-Debian and LibVEX; rerun with -h for copyright info
    ==2505== Command: ./a.out
    ==2505== 
    Voulez vous crypter ou decrypter un texte?(Ecrire C pour crypter et D pour decrypter)
    c
    Donner un texte a crypter
    hello
    Donner une cle de meme taille
    hello
    ==2505== Invalid write of size 1
    ==2505==    at 0x400AA4: encrypt (foo.c:15)
    ==2505==    by 0x4008C5: main (foo.c:66)
    ==2505==  Address 0x0 is not stack'd, malloc'd or (recently) free'd
    ==2505== 
    ==2505== 
    ==2505== Process terminating with default action of signal 11 (SIGSEGV)
    ==2505==  Access not within mapped region at address 0x0
    ==2505==    at 0x400AA4: encrypt (foo.c:15)
    ==2505==    by 0x4008C5: main (foo.c:66)
    ==2505==  If you believe this happened as a result of a stack
    ==2505==  overflow in your program's main thread (unlikely but
    ==2505==  possible), you can try to increase the size of the
    ==2505==  main thread stack using the --main-stacksize= flag.
    ==2505==  The main thread stack size used in this run was 8388608.
    ==2505== 
    ==2505== HEAP SUMMARY:
    ==2505==     in use at exit: 0 bytes in 0 blocks
    ==2505==   total heap usage: 0 allocs, 0 frees, 0 bytes allocated
    ==2505== 
    ==2505== All heap blocks were freed -- no leaks are possible
    ==2505== 
    ==2505== For counts of detected and suppressed errors, rerun with: -v
    ==2505== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 4 from 4)
    Segmentation fault
    ok thank you. Concerning the identation i am sorry,i am new to these things.
    concerning the problem, do you mean i should allocate memory with calloc .if yes,i tried with no benefit
    And one more think can you tell me which program you're using(i am using devc++).

  5. #5
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    Also here.

  6. #6
    Registered User
    Join Date
    May 2016
    Posts
    11

    Where is the problem ??

    Quote Originally Posted by jimblumberg View Post
    Also here.
    I don't understand where is the problem? i've got a problem which one community couldn't help me with, so i simply asked another community .

  7. #7
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    You need to leave at least 48 hours of no replies at all before deciding to move on.
    You're posting on several forums at the same time, in some attempt to gain special attention and hoping to get an answer quickly by spreading your bets.

    Except when the game is rumbled, we all find something else to do instead.

    You didn't read this in your other thread either
    How To Ask Questions The Smart Way
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Encryption and Decryption
    By dbz8gokugohan in forum C Programming
    Replies: 7
    Last Post: 12-02-2010, 07:40 AM
  2. encryption / decryption
    By ghatoz in forum C++ Programming
    Replies: 2
    Last Post: 11-18-2010, 06:45 AM
  3. Encryption/Decryption Help
    By coolage in forum C++ Programming
    Replies: 9
    Last Post: 04-25-2008, 01:53 AM
  4. Ask about Encryption and Decryption
    By ooosawaddee3 in forum C Programming
    Replies: 3
    Last Post: 07-19-2002, 12:55 AM
  5. Encryption/decryption algorithm
    By Abdi in forum C++ Programming
    Replies: 6
    Last Post: 04-27-2002, 05:09 AM

Tags for this Thread