Hey I'm taking the Hardvard CS50 course through ItunesU and I'm working on writing a code that will encrypt a message using the vigenere cipher which uses the
equation... Ci=(Pi+Kj)%26 where P is plaintext and K is the word to encrypt by.
I almost have it correct but I can't figure out how to make the ASCII letters wrap around from Z back to A and not go into other ASCII symbols. I've gotten the plain text to wrap around but not the key. Heres the code:
Code:
#include <stdio.h>
#include <string.h>
int main(void)
{
printf("What message would you like to encrypt?: \n");
char p[50];
fgets(p, 50, stdin);
printf("What would you like your keyword to be?(do not use caps): \n");
char key[15];
fgets(key, 15, stdin);
int i, n, j;
for(i = 0, j = 0, n = strlen(p); i < n; i++, j++)
{
if(p[i] <= 'A' && p[i] >= 'Z')
printf("%c", (((p[i] - 'A') + (key[j] - 'A' ) %26) + 'A'));
if(p[i] <= 'a' && p[i] >= 'z')
printf("%c", (((p[i] - 'a') + (key[j] - 'a' ) %26) + 'a'));
else if(p[i] >= 'A' && p[i] <= 'Z')
printf("%c", (((p[i] - 'A') + (key[j] - 'A') %26) + 'A'));
else if(p[i] >= 'a' && p[i] <= 'z')
printf("%c", (((p[i] - 'a') + (key[j] - 'a') %26) + 'a'));
else
printf("%c", p[i]);
}
printf("\n");
return 0;
}