I am trying to make a Vigenere cipher. My problem is that I'm not getting the expected output. When running the program it gives this output: HFNLP WPTLE. The correct output should be: HFNLP YOSND.
I think that the problem resides in the bad use of modulo (mod). When I try to wrap around the key (ABC) with the variable i
, the space (" ") in the plainText also wraps, affecting directly the result of the wrapping. I don't what to do in order to get the right output.
string plainText = "HELLO WORLD";
string keyword = "ABC";
for(int i = 0; i < strlen(plainText);i++)
{
int wrap = (int) strlen( keyword) % (int) strlen(plainText);
if(isalpha(plainText[i]))
{
int upper = 'A' + (plainText[i] + (toupper(keyword[i % wrap]))) % 26;
printf("%c", upper);
}
Index of keys on non-alphabetic characters must not increase.
An example of fix:
char *keyp = keyword;
char ch;
for(int i = 0; ch = plainText[i]; i++){
if(isalpha(ch)){
putchar('A' + (toupper(ch) - 'A' + toupper(*keyp++) - 'A') % 26);
if(!*keyp)
keyp = keyword;
} else
putchar(ch);
}