Vigenere cipher and C program

Share

Text is encrypted and decrypted using the Vigenere cipher algorithm. An algorithm for encrypting an alphabetic text called the Vigenere cipher uses a number of interconnected Caesar ciphers. Its foundation is a keyword’s letter structure. Such a substitution cipher uses polyalphabetic characters. Understanding and using this algorithm are simple. Giovan Battista Bellaso introduced this algorithm for the first time in 1553.

Algorithm

  1. Input the plaintext and the keyword.
  2. Repeat the keyword to make it the length of the plaintext.
  3. Encryption: Perform modular addition of the repeating keyword and the plaintext.
    Ci = Pi + Ki(mod m)
    Where Ci is the cipher text,
    Pi is the plaintext,
    Ki is the repeating keyword and ‘m’ is the length of the alphabet.
  1. Decryption: Perform modular subtraction of key phrases from the cipher text.
    Pi = Ci – Ki
    (mod m)
  2. Display the encrypted and decrypted message as well.

Let’s suppose Key = CIPHER, so m=6. Then,

K=(2,8,15,7,4,17)

Also, suppose plaintext, P = “he is a good boy”.

Now encryption is done by grouping plain text into groups of ‘m’ letters.

So, P = heisag oodboy = (7,4,8,18,0,6,14,14,3,1,14,24)

since, CI = Pi+Ki, CI = (9,12,23,25,4,23,16,22,18,8,16,17) = JMXZEZQWSIQR

C Program

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include<stdlib.h>

void encrypt(){
    unsigned int i, j; 
    char plain[127];
    char key[15];
    gets();
    printf("\n Enter the plaintext (maximum 128 characters): ");
    gets(plain);
    printf("\n Enter the key (maximum 16 characters): ");
    gets(key);
    printf("\n Cipher Text: ");
    for (i = 0, j = 0; i < strlen(plain); i++, j++){
        if (j >= strlen(key)){
            j = 0;
        }
        printf("%c", 65 + (((toupper(plain[i]) - 65) + (toupper(key[j]) - 65)) % 26));
    }
    printf("\n");
}

void decrypt(){
    unsigned int i, j;
    char plain[127];
    char key[15];
    int value;
    printf("\n Enter the ciphertext: ");
    gets(plain);
    printf("\n Enter the key: ");
    gets(key);
    for (i = 0, j = 0; i < strlen(plain); i++, j++){
        if (j >= strlen(key)){
            j = 0;
        }
        value = (toupper(plain[i]) - 64) - (toupper(key[j]) - 64);
        if (value < 0){
            value = value + 26;
        }
        printf("%c", 65 + (value % 26));
    }
}


int main(){
    int option;
    while (1){
        printf("\n 1. Encipher!!");
        printf("\n 2. Decipher!!");
        printf("\n 3. Exit \n");
        printf("\n Enter your option: ");
        scanf("%d", &option);
        if (option == 3)
            exit(0);
        else if (option == 1)
            encrypt();
        else if (option == 2)
            decrypt();
        else
            printf("\n Invalid selection!!Try again!! ");
    }
    return 0;
}
Share
Sudeep Mishra

Sudeep Mishra

Healing

%d bloggers like this: