I have been stuck on this for a while now, I thought I had it working several times only to find more things I forgot. Basically the problem set was to create the Vigenere Cipher using C, the rules can be found here
I basically have it working it will only allow the correct characters and if the keyword is the same length as the message all is good.
The issue I am having is figuring a way to reset the looping of the keyword while the message is being encrypted, so if I enter a keyword 'A' and the message 'This is a test' the encrypted message should read 'This is a test' since 'A' is worth zero shifts along the ASCII table.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
int main(int argc, char * keyWord[]) {
int cipher[64], i, j, k, l;
char message[128];
// Validation - using alphaCheck Function
if (argc != 2 || alphaCheck(keyWord) == 2) {
return 1;
}
// For loop to convert to upper and set value ie A = 0 B = 1
for (i = 0, j = strlen(keyWord[1]); i < j; i++) {
cipher[i] = (toupper(keyWord[1][i]) - 65);
printf("%i\n", cipher[i]);
}
// Prompt the user for the message to encrypt
printf("Enter your secret message: ");
fgets(message, 128, stdin);
int keyCount = 0;
int p = strlen(keyWord[1]);
if (keyCount < p) {
keyCount++;
} else {
keyCount = 0;
}
for (i = 0, k = strlen(message); i < k; i++) {
if (isspace(message[i])) {
printf(" ");
} else if (isupper(message[i])) {
char c = (message[i] - 65 + cipher[i]) % 26 + 65;
printf("%c", c);
}
else {
char d = (message[i] - 97 + cipher[i]) % 26 + 97;
printf("%c", d);
}
}
}
// Function to check if alphabet characters.
int alphaCheck(char * argv[]) {
int length = strlen(argv[1]), n;
for (n = 0; n < length; n++) {
if (!isalpha(argv[1][n])) {
printf("Characters 'A-Z' for Keyword.\n");
return 2;
}
}
}
The following section is redundant at the moment I left it in to show how I tried to tackle the problem but failed.
int keyCount = 0;
int p = strlen(keyWord[1]);
if (keyCount < p) {
keyCount++;
} else {
keyCount = 0;
}