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?
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):