Search This Blog

Tuesday, 17 September 2024

Ex-2: Implementing Play-fair Cipher for Encryption/Decryption

0 comments

Implementation in C:

#include<stdio.h>
void main()
{
    char ch, msg[250];
    char crypt[9][9] = {{'a','e','i','o','u','b','c','d','.'},{'f','g','h','j','k','l','m','n',','},{'p','q','r','s','t','v','w','x','/'},{'y','z','0','1','2','3','4','5','-'},{'6','7','8','9','A','E','I','O','+'},{'U','B','C','D','F','G','H','J','?'},{'K','L','M','N','P','Q','R','S',':'},{'T','V','W','X','Y','Z',' ','!',';'},{'`','~','@','#','$','%','^','&','*'}};
    char ctxt[250];
    char dtxt[250];
    int i=0,j,k,l=0,m,n;
    printf("Enter Your Message\n");
    do
    {
        scanf("%c", &ch);
        if (ch==10)
        {
            msg[i]='\0';
            ctxt[i]='\0';
            break;
        }
        else
        {
            if(ch==' ')
                l=0;
            l++;
           
            msg[i]=ch;
            for(j=0;j<9;j++)
                for(k=0;k<9;k++)
                    if(ch==crypt[j][k])
                    {
                        m = j;
                        n = k;
                        n = n+l;
                        if(n>=9)
                        {
                            n=n-9;
                            m++;
                        }
                        if(m>=9)
                        {
                            m=m-9;
                        }       
                        ctxt[i]=crypt[m][n];
                    }
        }
        i++;
    }
    while(1);
    printf("\nYour Input Message is: %s\n", msg);
    printf("\nThe Cipher Text is : %s\n", ctxt);
    i=0,l=0;
    while(ctxt[i]!='\0')
    {
        ch=ctxt[i];
        if(ch=='!')
            l=0;       
            l++;
           
            for(j=0;j<9;j++)
                for(k=0;k<9;k++)
                    if(ch==crypt[j][k])
                    {
                        m = j;
                        n = k;
                        n = n-l;
                        if(n<0)
                        {
                            n=n+9;
                            m--;
                        }
                        if(m<0)
                            m=m+9;
                        dtxt[i]=crypt[m][n];
                    }
            i++;
    }
    dtxt[i]='\0';
    printf("\nThe Original Text is : %s", dtxt);
}

Leave a Reply