Thursday, 8 November 2012

Knapsack Cryptosystem: Encryption (Java)


import java.util.*;
class KnapSack
{
public void calculateKnapSack(char ch,int b[],int p[],int n,int r)
{
int pt=ch;
int sum=0;
String str=Integer.toBinaryString(pt);
int t[]=new int[7];
int a[]=new int[7];
int x[]=new int[7];
for(int h=0;h<7;h++)
t[h]=(b[h]*r)%n;
System.out.print("\nTemparory Tuple:\t\t\t");
for(int h=0;h<7;h++)
System.out.print(t[h]+",");
for(int h=0;h<7;h++)
a[h]=t[p[h]-1];
System.out.print("\nAfter Permuting Temporary Tuple:\t");
for(int h=0;h<7;h++)
System.out.print(a[h]+",");
for(int h=0;h<7;h++)
x[h]=str.charAt(h)-48;
System.out.print("\nAfter (b*n)%r:\t\t\t\t");
for(int h=0;h<7;h++)
System.out.print(a[h]*x[h]+",");
for(int h=0;h<7;h++)
sum+=a[h]*x[h];
System.out.println("\n\nThe Sum and the Cipher Text is:"+sum);
System.out.println();
}
public static void main(String args[])
{
String ch;
Scanner se=new Scanner(System.in);
System.out.println("\nEnter the plain text: ");
ch=se.nextLine();
char pt=ch.charAt(0);
int b[]=new int[7];
int p[]=new int[7];
System.out.print("Enter the value of N: \n");
int n=se.nextInt();
System.out.print("Enter the superincreasing tuple upto 7: \n");
for(int i=0;i<7;i++)
b[i]=se.nextInt();
System.out.print("Enter the permutation tuple upto 7: \n");
for(int i=0;i<7;i++)
p[i]=se.nextInt();
KnapSack l=new KnapSack();
l.calculateKnapSack(pt,b,p,n,41);
}
}



Download the code from here

0 comments:

Post a Comment