Vigenere Cipher:
Vigenere 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.
This is the code in C:
// C program to implement vigenere cipher
#include<stdio.h>
#include<string.h>
//function for encryption
void encryption(const char *text,const char *keyword)
{
int len=strlen(text);
char entext[len+1];
memset(entext, '\0', sizeof(entext));
for(int i=0;i<len;i++)
{
entext[i]= (text[i] + keyword[i])%26 +'A';
}
printf("%s", entext);
}
//function for decryption
void decryption(const char *cipher,const char *keyword)
{
int len=strlen(cipher);
char detext[len+1];
memset(detext, '\0', sizeof(detext));
for(int i=0;i<len;i++)
{
detext[i]= (cipher[i]- keyword[i] +26)%26 +'A';
}
printf("%s", detext);
}
int main()
{
char text[100], key[100], cipher[100];
int textLen, keyLen, ciphLen; //variables to store length of plain text, key and cipher text respectively
int n;
int option;
printf("This is a C program to implement Vigenere Cipher. \n\nEnter: 1. Encryption \n2. Decryption\n");
scanf("%d",&option);
if(option==1)
{
printf("You have chosen Encryption. \nEnter the plain text: ");
scanf("%s", text); //user input of only uppercase characters without white spaces
textLen= strlen(text);
n=textLen;
printf("Enter the key: ");
scanf("%s", key);
keyLen= strlen(key);
}
else if(option==2)
{
printf("You have chosen Decryption. \nEnter the Cipher text(Encrypted text): ");
scanf("%s", cipher);
ciphLen=strlen(cipher);
n=ciphLen;
printf("Enter the key: ");
scanf("%s", key);
keyLen= strlen(key);
}
else
{
printf("Wrong option entered! Enter either 1(for encryption) or 2(for Decryption)");
return 0;
}
//Generating the keyword(new key)
int i,j;
char keyword[100];
for(i=0,j=0;i<n;i++,j++)
{
if(j==keyLen)
j=0;
keyword[i]=key[j];
}
if(option==1)
{
printf("The encrypted text(cipher text) is: ");
encryption(text,keyword);
}
else
{
printf("The decrypted text(plain text) is: ");
decryption(cipher,keyword);
}
printf("\n");
return 0;
}
Log in or sign up for Devpost to join the conversation.