Tuesday, 27 November 2012

Knapsack Cryptosystem: Decryption (Java)


Knapsack Cryptosystem: Decryption


import java.util.*;
class KSD
{
public int inverse(int a,int n)
{
int r1,r2,r,q,t1,t2,t;
r1=n;r2=a;
t1=0;t2=1;
while(r2>0)
{
q=r1/r2;
   r=r1-q*r2;
   t=t1-q*t2;

   r1=r2;r2=r;
   t1=t2;t2=t;
}
 if(r1==1)
  return t1;
 else
  return 0;
}
public void invKnapSack(int a[],int s,int p[])
{
int s2,sum=0;
int x[]=new int[7];
int t[]=new int[7];

System.out.println("\n\n i\ta\ts\tx\ts\n");
for(int h=6;h>=0;h--)
{
if(s>=a[h])
{
x[h]=1;
}
s2=s-(a[h]*x[h]);
System.out.println(h+"\t"+a[h]+"\t"+s+"\t"+x[h]+"\t"+s2);
s=s2;
}

/*for(int h=0;h<7;h++)
System.out.print(x[h]);*/
for(int h=0;h<7;h++)
t[h]=x[p[h]-1];
System.out.println();
for(int h=0;h<7;h++)
{
int temp;
if(t[h]==1)
{
temp=(int)(Math.round((Math.pow(2,7-h-1))));
sum+=temp;
}
}
char ch=(char)sum;
System.out.println("The plain text is: "+ch);
}
}
class KnapSackDecrypt
{
public static void main(String args[])
{
int b,n,r;
int a[]=new int[7];
int p[]=new int[7];
Scanner se=new Scanner(System.in);
System.out.println("Enter the super increasing tuple: ");
for(int h=0;h<7;h++)
a[h]=se.nextInt();
System.out.println("Enter the permutation tuple: ");
for(int h=0;h<7;h++)
p[h]=se.nextInt();
System.out.println("Enter the cipher text (sum) : ");
b=se.nextInt();
se.nextLine();
System.out.println("Enter the N: ");
n=se.nextInt();
se.nextLine();
System.out.println("Enter the R: ");
r=se.nextInt();
//System.out.println(b);
KSD ksd=new KSD();
int s=ksd.inverse(r,n);
s*=b;
s%=n;
System.out.println(s);
ksd.invKnapSack(a,s,p);
}

}

Download the code from here

0 comments:

Post a Comment