Implement a cryptographic system using the Vigenre cipher method. - C Data Structure

C examples for Data Structure:Encrypt Decrypt

Description

Implement a cryptographic system using the Vigenre cipher method.

Demo Code

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

char *msgOriginal = "this is a test";
char msgEncrypt[100];
char msgDecrypt[100];
char msgKey[15];/*from  ww  w .  java  2 s. c  o m*/
int intChoice, lenKey, lenMsg, intKey[15];

void getKey()
{
  int i, j;
  fflush(stdin);
  printf("\nEnter TEXT KEY in FULL CAPS, Do Not Include Spaces and \n");
  printf("Punctuation Symbols (upto 15 characters): \n");
  gets_s(msgKey);
  lenKey = strlen(msgKey);
  for(i = 0; i < lenKey; i++)
        intKey[i] = msgKey[i] - 65;
}

void encryptMsg()
{
  int i, j, ch;
  fflush(stdin);
  lenMsg = strlen(msgOriginal);
    for(i = 0; i < lenMsg; i++) {
      j = i % lenKey;
      ch = msgOriginal[i];
      if(ch >= 'a' && ch <= 'z') {
        ch = ch + intKey[j];
        if(ch > 'z')
          ch = ch - 'z' + 'a' - 1;
         msgEncrypt[i] = ch;
      }
      else if(ch >= 'A' && ch <= 'Z'){
        ch = ch + intKey[j];
        if(ch > 'Z')
          ch = ch - 'Z' + 'A' - 1;
        msgEncrypt[i] = ch;
      }
    }
  msgEncrypt[lenMsg] = '\0';
  printf("\nEncrypted Message: %s", msgEncrypt);
}

void decryptMsg()
{
  int i, j, ch;
  fflush(stdin);
  printf("Enter the Message to be Decrypted (upto 100 alphabets):\n");
  gets_s(msgEncrypt);
  lenMsg = strlen(msgEncrypt);
  for(i = 0; i < lenMsg; i++) {
    j = i % lenKey;
    ch = msgEncrypt[i];
    if(ch >= 'a' && ch <= 'z') {
      ch = ch - intKey[j];
      if(ch < 'a')
        ch = ch + 'z' - 'a' + 1;
      msgDecrypt[i] = ch;
    }
    else if(ch >= 'A' && ch <= 'Z'){
      ch = ch - intKey[j];
      if(ch < 'A')
        ch = ch + 'Z' - 'A' + 1;
      msgDecrypt[i] = ch;
    }
  }
  msgDecrypt[lenMsg] = '\0';
  printf("\nDecrypted Message: %s", msgDecrypt);
}

void main()
{
  getKey();
  encryptMsg();
  decryptMsg();
}

Result


Related Tutorials