Search code examples
cencryptioncryptographyvigenere

C programming - Trying to make Vigenere encryption/decryption program


Can you take a look on this code please?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


char encrypt(char *abc, int *key,char text, int counter)
{
   int i;
   int encryptedletter;


   for(i=0;i<=25;i++)
   {
     if(text==abc[i])
     {
     encryptedletter = (i + key[counter])%26 ;
     return abc[encryptedletter];
     }
   }

}


char decrypt(char *abc, int *key,char text, int counter)
{
  int i;
  int decryptedletter;


  for(i=0;i<=25;i++)
  {
    if(text==abc[i])
    {
      decryptedletter = (i-key[counter])%26 ;
      return abc[decryptedletter];
    }
  }

}





int main(void)
{
  char text[100];
  char encryped[100];
  char decrypted[100];
  char key[20];
  int i,z,q,keylength,counter=0;
  char abc[27]= "abcdefghijklmnopqrstuvwxyz"; //ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789        .";
  int keyint[70];

  printf("Give Text: ");
  gets(text);

  printf("Give Password: ");
  gets(key);

  keylength = strlen(key);

  for(z=0;z<strlen(key);z++)
  {
     for(i=0;i<=25;i++)
     {
        if(key[z]==abc[i]) keyint[z] = i;
     }
  }


//~~~~~~~~~~~~~~~~~~~~~~~~~~ENCRYPTION~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  for(i=0;i<strlen(text);i++)
  {
     if(counter>=keylength) counter=0;
     encryped[i] = encrypt(abc,keyint,text[i],counter);
     counter++;

  }
  encryped[strlen(text)]='\0';
  printf("\nEncrypted text: %s\n", encryped);

//~~~~~~~~~~~~~~~~~~~~~~~~~~DECRYPTION~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
counter =0;

for(q=0;q<=strlen(text);q++)
{
    if(counter>=keylength) counter=0;
    decrypted[q] = decrypt(abc,keyint,encryped[q],counter);
    counter++;
    printf("%c", decrypted[q]);
}


  return 0;
}

I'm trying to make an encryption/decryption program based on Vigenere.

I think it's working fine.. but when letters of text or password are higher than 'T'(not sure) on my abc array then i get back wrong decrypted text.


Solution

  • you need to consider the case when you never enter if(text==abc[i]) within encrypt() and decrypt(). what is the return value that you write into the encrypted/decrypted in that case?

    you might want to return text unencrypted so that you preserve spaces, punctuation etc, and thus ensure that both encrypted and decrypted messages are of length strlen(text)

    finally, decryptedletter = ((i-key[*counter])%26) can become negative so that you can't use it as an index for abc[decryptedletter]. in that case, you need to "wrap it around" e.g. by

    if(decryptedletter<0) decryptedletter += 26;