I'm trying to make a Vigenere cipher code in C and I have done something that is wrong and I can't fix it... How do understand that something goes wrong? Well I have some examples with keyword and result cipher with Vigenere cipher like
- keyword:
bacon
- text:
Meet me at the park at eleven am
- correct result:
Negh zf av huf pcfx bt gzrwep oz
- my code result with same text and keyword:
Tegh ne og tjs qaty bt syfvgb bm
Code:
int main(int argc, string argv[])
{
string keyWord;
if( argc != 2 )
{
printf("Wrong Argument");
return 1;
}
else
{
keyWord = argv[1];
//check if argument is
//only alphabetical characters
for(int i = 0; i < strlen(keyWord); i++)
{
char c = keyWord[i];
if( !isalpha(c) )
{
printf("Your Keyword Must Contain Only alphabetical characters\n");
return 1;
}
}
}
//todo
printf("Enter Plain Text\n");
string plainText = GetString();
for(int i = 0; i < strlen(plainText); i++)
{
char c = plainText[i];
int keyWordWrapper;
char keyC;
if(isalpha(c))
{
keyWordWrapper = i % strlen(keyWord);
keyC = keyWord[keyWordWrapper];
if(islower(c))
{
int key = keyC - 'a';
c = (c - 'a' + key) % 26 + 'a';
}
if(isupper(c))
{
int key = keyC - 'A';
c = (c - 'A' + key) % 26 + 'A';
}
}
printf("%c",c);
}
printf("\n");
return 0;
}
GetString()
is declared in a header and defined in a library that I'm using (it's like scanf
).
this is the updated code
int main(int argc, string argv[])
{ string keyWord;
if( argc != 2 )
{
printf("Wrong Argument");
return 1;
}
else
{
keyWord = argv[1];
//check if argument is
//only alphabetical characters
for(int i = 0; i < strlen(keyWord); i++)
{
char c = keyWord[i];
if( !isalpha(c) )
{
printf("Your Keyword Must Contain Only alphabetical characters\n");
return 1;
}
}
}
string plainText = GetString();
int j;
for(int i = 0; i < strlen(plainText); i++)
{
j++;
char c = plainText[i];
int keyWordWrapper;
char keyC;
if(j > strlen(keyWord))
j = 0;
if(isalpha(c))
{
keyWordWrapper = i % strlen(keyWord);
keyC = keyWord[keyWordWrapper];
int key;
tolower(c);
if(islower(keyC))
key = keyC - 'a';
if(isupper(keyC))
key = keyC - 'A';
c = (c - 'a' + key) % 26 + 'a';
}
printf("%c",c);
}
printf("\n");
return 0; }