Question

I'm writing a program for Vigenere Cipher. But I don't know how to make my key repeat til the end of my plain text. Right now what my code does is encrypt only the letters which are equivalent to the number of letter my key has. For example I enter a key of "dog" and my plain text is "catdog", it gives me an encrypted text of "fozdyw". Which means it is only encrypting the first 3 letters.

This is a bit of my code that does the encrypting:

for (int j=0, k=0; j < strlen(text); j++, k++)
      {         
        if((text[j] >= 'A') && (text[j] <= 'Z'))
            text[j] = ((text[j] -'A') + key[k]) % 26 +'A';

        if((text[j] >= 'a') && (text[j] <= 'z'))
            text[j] = ((text[j] -'a') + key[k]) % 26 +'a';

        printf("%c", text[j]); 
      }  

What am I doing wrong? And what should be the right thing to do?

Was it helpful?

Solution

When you get to the end of the key, go back to index 0, this is done by using the remainder of the division by the size of the key (AKA modulus):

  for (int j=0, k=0; j < strlen(text); j++, k++)
  {         
    if((text[j] >= 'A') && (text[j] <= 'Z'))
        text[j] = ((text[j] -'A') + key[k % size_of_the_key]) % 26 +'A';

    if((text[j] >= 'a') && (text[j] <= 'z'))
        text[j] = ((text[j] -'a') + key[k % size_of_the_key]) % 26 +'a';

    printf("%c", text[j]); 
  }  

OTHER TIPS

the ascii table is a good reference for that. that is, preventing symbols from being encrypted. to be precise, endavour to work with a speific range of letters. for instance between 65 and 90 for uppercase else terminate that program.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top