Wednesday, March 13, 2013

PolyAlphabetic_cipher in Java


import java.util.*;
public class PolyAlphabetic
{
char alphabets[][]=new char[26][26];
Scanner s,s1;
String key,plntxt,enctxt,ciptxt,dectxt;

public PolyAlphabetic()
{
assign();
s=new Scanner(System.in);
s1=new Scanner(System.in);
System.out.println("Press 1 to Encrypt a plain text \nPress 2 to Decrypt a cipher text ");
int input=s1.nextInt();
if(input==1)
{
System.out.print("Enter the key :");
key=s.nextLine();
System.out.print("Enter the text to be encrypt :");
plntxt=s.nextLine();
encrypt(plntxt, key);
}

if(input==2)
{
System.out.print("Enter the key :");
key=s.nextLine();
System.out.print("Enter the text to be decrypt :");
ciptxt=s.nextLine();
decrypt(ciptxt, key);
}

//print();
}
public void assign()
{
for(int i=0;i<26;i++)
{
for(int j=0;j<26;j++)
{
alphabets[i][j]=(char)(((i+j)%26)+97);
}
}
}
public void print()
{
for(int i=0;i<26;i++)
{
for(int j=0;j<26;j++)
{
System.out.print(alphabets[i][j]+" ");
}
System.out.println();
}
}

public void encrypt(String text, String k)
{
String str="";
for(int i=0;i<text.length();i++)
{
str=str+alphabets[(int)(k.charAt(i%k.length()))-97][(int)text.charAt(i)-97];

}
enctxt=str;
System.out.println("Encrypted text is "+enctxt);
}

public void decrypt(String text, String k)
{
String str="";
for(int i=0;i<text.length();i++)
{
for(int j=0;j<26;j++)
{
if(alphabets[(int)(k.charAt(i%k.length()))-97][j]==text.charAt(i))
str=str+alphabets[0][j];
}
}
dectxt=str;
System.out.println("Decrypted text is "+dectxt);
}
public static void main(String args[])
{
PolyAlphabetic pa=new PolyAlphabetic();
}
}

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home