Reputation: 4163
I am having a terrible time understanding how to get the wrapper to work with these encryption programs. I got a Caesar cipher program to work to both encrypt and decrypt, now I am working on a Vigenere cipher. I have the program working but when I use a key that will cause the letters to wrap around I get odd results. Here is the code I am using:
int main(int argc, char *argv[])
{
char s2[25];
strcpy(s2, argv[1]);
printf("Please enter a string of text to be encrypted!\n");
string p = GetString();
for (int i = 0, n = strlen(p); i < n; i++)
{
if (isupper(p[i])){
char c = (p[i] - 'A' + s2[i]);
printf("%c", c);
}
}
printf("\n");
}
This code will work if the command line input is ./program BACON
and I enter BLAH for the text to be encrypted. If for example I use ./program ZZZZZ
as the key then I will get all kinds of odd results because it does not wrap back around. I have tried using the modulus operator and have left it out of the code I just posted because I still could not get it to wrap with that. I am just starting to learn programming.
Maybe you can help me understand the math better; your code works perfectly, but I have been trying to figure this out on a calculator manually just to see what's going on. This is what I have so far:
./program HHHHH
keyLen should equal 5 in my understanding and so if I give p[i] a value of "H"
keyLen= 5
p[i]= H //or 72 in ASCII
int sum = (p[i] - 'A') + (s2[i % keyLen] - 'A'); //sum = (72 - '65') + ([72 % 5] - '65');
char c = 'A' + sum%26; // c = 65 + -11
Maybe my math is way off because when I do things in the order I think they should be done sum = negative 63 and so a 26 mod of -63 which gives me negative 11. Which clearly is not right because that equals 54 when you add 65 and negative 11.
Even if I make the negative 11 a positive integer of 11 and add 65 I get 76 which is ASCII character "L" but the right answer is "O". I am clearly doing something wrong but I've been working on the solution for a while now and keep coming up with the same results.
Upvotes: 0
Views: 129
Reputation: 726579
There are two "wrap-around" issues in your program:
Here is how you fix it: right after copying the key into s2
, do this:
int keyLen = strlen(s2);
Now inside your loop do this:
int sum = (p[i] - 'A') + (s2[i % keyLen] - 'A'); // Calculate the sum of key+word
char c = 'A' + sum%26; // Wrap around at 26, the number of letters in the alphabet
This will make the output look "normal".
Once you figure out how the last formula works, you should be able to modify it to decode the word.
Upvotes: 2