The BOTTOM LINE Quote Of The Day

The BOTTOM LINE Quote Of The Day

Don't Ever Tell GOD How BIG Your Problems are.
Just Tell Your Problems How BIG your GOD is ;)

Monday, November 12, 2012

Implement Playfair substitution cipher encryption and decryption technique

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

char mssg[100]; 
char dmssg[200];
int ind[200];

char table[][5] = { {'M','O','N','A','R'}, {'C','H','Y','B','D'}, 
                    {'E','F','G','I','K'}, {'L','P','Q','S','T'}, 
                    {'U','V','W','X','Z'}
                  };
struct pos
{
  int i;
  int j;      
}a1,a2;
 
void get_mssg()
{
   printf("\n Enter the Plaintext (in caps): ");
   gets(mssg);
}

struct pos get_pos(char ch)
{
  struct pos t;
  for(t.i = 0; t.i < 5; t.i++)
  {
   for(t.j = 0; t.j < 5; t.j++)
   {
     if(table[t.i][t.j] == ch)
      return t;      
   }     
  }      
}

void set_pos(struct pos a1, struct pos a2, int & l)
{
  if(a1.i == a2.i)
  {
    dmssg[l] = table[a1.i][(a1.j+1)%5];    dmssg[l+1] = table[a2.i][(a2.j+1)%5];        
  }
  else if(a1.j == a2.j)
  {
    dmssg[l] = table[(a1.i+1)%5][a1.j];    dmssg[l+1] = table[(a2.i+1)%5][a2.j];        
  }
  else
  {
    dmssg[l] = table[a1.i][a2.j];          dmssg[l+1] = table[a2.i][a1.j]; 
  }     
}

void set_pos2(struct pos a1, struct pos a2, int & l)
{
  if(a1.i == a2.i)
  {
    mssg[l] = table[a1.i][a1.j == 0 ? 4 : a1.j-1];
    mssg[l+1] = table[a2.i][a2.j == 0 ? 4 : a2.j-1];        
  }

  else if(a1.j == a2.j)
  {
    mssg[l] = table[a1.i == 0 ? 4 : a1.i-1][a1.j];
    mssg[l+1] = table[a2.i == 0 ? 4 : a2.i-1][a2.j];        
  }
  else
  {
    mssg[l] = table[a1.i][a2.j];
    mssg[l+1] = table[a2.i][a1.j]; 
  }     
}

void en_mssg()
{
  int k =0,l = 0;
  while(k < strlen(mssg))
  {
    a1 = get_pos(mssg[k]);

    if(mssg[k+1] == '\0' || mssg[k+1] == mssg[k])
     a2 = get_pos( ((mssg[k] - 65 + 12) % 26)+65 );
    else
     a2 = get_pos(mssg[k+1]);
      
    set_pos(a1,a2,l);
   
    ind[l] = 0;
    if(mssg[k+1] == '\0' || mssg[k+1] == mssg[k])
    {
      ind[l+1] = 1;
      k++;           
    }
    else
    {
      ind[l+1] = 0;      
      k += 2; 
    }
    l += 2;         
  }  
  dmssg[l] = '\0';
  printf("\n The Ciphertext is : ");
  puts(dmssg);
}

void de_mssg()
{
  int k = 0;
  int l = 0;

  while(k < strlen(dmssg))
  {
    a1 = get_pos(dmssg[k]);   
    a2 = get_pos(dmssg[k+1]);
       
    set_pos2(a1,a2,l);
   
    if(ind[k+1] == 1)
     l += 1;   
    else
     l += 2;   
    k += 2;         
  }  
  mssg[l] = '\0';
 
  printf("\n The Decrypted Plaintext is : ");
  puts(mssg);
}

int main()
{
  get_mssg();
  en_mssg();
  de_mssg(); 
  getch();
  return 0; 
}

No comments:

Post a Comment