The Vigenère cipher is a method of encrypting alphabetic text. It uses a simple form of polyalphabetic substitution. A polyalphabetic cipher is any cipher based on substitution, using multiple substitution alphabets. The encryption of the original text is done using the Vigenère square or Vigenère table.
The table consists of the alphabets written out 26 times in different rows, each alphabet shifted cyclically to the left compared to the previous alphabet. At different points in the encryption process, the cipher uses a different alphabet from one of the rows. The alphabet used at each point depends on a repeating keyword.
To generate the key, we first create a matrix of alphabets A-Z. The key is then written horizontally at the top of the matrix. The length of the key must be less than or equal to the length of the message.
For example, if our message is "HELLO" and our key is "ABC", the first letter of the message will be encrypted using the first letter of the key, the second letter using the second letter, and so on. When we reach the end of the key, we start again from the beginning.
To encrypt the message, we match the row with the key letter and the column with the message letter. The letter in the intersecting cell is the encrypted letter.
To decrypt the message, we use the same process but this time we match the row with the key letter and the column with the encrypted letter. The letter in the intersecting cell is the original message letter.
Now that we have a basic understanding of the Vigenère cipher, let's implement it in C.
First, we need to include the necessary libraries and define the key and message as strings:
#include <stdio.h> #include <string.h>
char key[] = "ABC"; char message[] = "HELLO";
Next, we define the functions for encrypting and decrypting the message:
void encrypt() { int i, j; char encrypted[strlen(message)];
for(i = 0, j = 0; i < strlen(message); i++, j++)
{
if(j == strlen(key))
{
j = 0;
}
encrypted[i] = (message[i] + key[j]) % 26;
}
printf("Encrypted message: %s\n", encrypted);
}
void decrypt() { int i, j; char decrypted[strlen(message)];
for(i = 0, j = 0; i < strlen(message); i++, j++)
{
if(j == strlen(key))
{
j = 0;
}
decrypted[i] = (message[i] - key[j] + 26) % 26;
}
printf("Decrypted message: %s\n", decrypted);
}
Finally, we can call these functions in the main function:
int main() { printf("Original message: %s\n", message);
encrypt();
decrypt();
return 0;
}
And that's it! We now have a working Vigenère cipher program in C. This program can be used to encrypt and decrypt messages using the Vigenère cipher. Of course, this is just a basic implementation and there are many ways to improve upon it