Upload
arundhang
View
224
Download
2
Tags:
Embed Size (px)
DESCRIPTION
Ty It Ns Practicals
Citation preview
// Program for implementing polycipher
package polyciipher;
import java.util.*;
public class PolyCiipher
{
public static void main(String[] args)
{
int[] j = new int[100];
int[] s = new int[100];
String test="";
// initialization of the Scanner class,handles input from user,can be found in the java.util.*; library.
// we are creating object "in" from the scanner and telling java that this will be System input
try{
Scanner in = new Scanner(System.in);
System.out.println("Enter the plain text(STRING SHOULD BE IN UPPERCASE AND DONT GIVE SPACE BETWEEN WORDS)::");
// next() is a method which gets the next string of text that a user types on the keyboard
test = in.nextLine();
for ( int i = 0; i < test.length(); ++i ) {
char c = test.charAt( i );// "c" holds the individual character of the string
s[i] = (int) c-65;
}
for(int i=0;i<test.length()-1;i++){
j[i+1]=s[i];
}
System.out.println("Enter the key::");
int k = Integer.parseInt(in.nextLine());
j[0]=k;
System.out.println();
System.out.println("The position of the character in the cipher text::");
for(int i=0;i<test.length();i++){
j[i]=j[i]+s[i];
j[i]=j[i]%26;
System.out.print(j[i]);
}
System.out.println();
System.out.println("The cipher text::");
for(int i=0;i<test.length();i++){
char c=(char) (j[i]+65);
System.out.print(c);
}
System.out.println();
}
catch(Exception er){
System.out.println("--YOU HAVE TYPE INVALID DATA--");
}
}
}
----------------------------------------------------------output---------------------------------------------------------------
Enter a string(STRING SHOULD BE IN ASCII AND DONT GIVE SPACE BETWEEN WORDS)::
ATTACKISTONIGHT
Enter the key::
12
1219121921218011712114130
MTMTCMSALHBVONA
BUILD SUCCESSFUL (total time: 16 seconds)
// Program for implementing Transposition ciphers
import java.awt.event.*;
import java.util.*;
public class transpositionCipher
{
public static void main(String args[])
{
String key;
String message;
String encryptedMessage;
// Letters in the x-axis
int x=0;
// Letters in the y-axis
int y=0;
key = "tape";
message = "CRYPTOGRAPHYDEMO";
encryptedMessage = "";
// To set the temp as [x][y]
char temp[][]=new char [key.length()][message.length()];
char msg[] = message.toCharArray();
// To populate the array
x=0;
y=0;
// To convert the message into an array of char
for (int i=0; i< msg.length;i++)
{
temp[x][y]=msg[i];
if (x==(key.length()-1))
{
x=0;
y=y+1;
} // Close if
else
{
x++;
}
} // Close for loop
// To sort the key
char t[]=new char [key.length()];
t=key.toCharArray();
Arrays.sort(t);
for (int j=0;j<y;j++)
{
for (int i=0;i<key.length();i++)
{
System.out.print(temp[i][j]);
}
System.out.println();
}
System.out.println();
// To print out row by row (i.e. y)
for (int j=0;j<y;j++)
{
// To compare the the sorted Key with the key
// For char in the key
for (int i=0;i<key.length();i++)
{
int pos=0;
// To get the position of key.charAt(i) from sorted key
for (pos=0;pos<t.length;pos++){
if (key.charAt(i)==t[pos]){
// To break the for loop once the key is found
break;
}
}
System.out.print(temp[pos][j]);
encryptedMessage+=temp[pos][j];
}
System.out.println();
}
System.out.println(encryptedMessage);
System.exit(0);
}
}
OutPut
PCYR
RTGO
YAHP
ODME
PCYRRTGOYAHPODME
BUILD SUCCESSFUL (total time: 3 seconds)
// Program for implement Rail fence cipher in Java
// File Name: RailFence.java
import java.util.*;
class RailFenceBasic
{
int depth;
String Encryption(String plainText,int depth)throws Exception
{
int r=depth,len=plainText.length();
int c=len/depth;
char mat[][]=new char[r][c];
int k=0;
String cipherText="";
for(int i=0;i< c;i++)
{
for(int j=0;j< r;j++)
{
if(k!=len)
mat[j][i]=plainText.charAt(k++);
else
mat[j][i]='X';
}
}
for(int i=0;i< r;i++)
{
for(int j=0;j< c;j++)
{
cipherText+=mat[i][j];
}
}
return cipherText;
}
String Decryption(String cipherText,int depth)throws Exception
{
int r=depth,len=cipherText.length();
int c=len/depth;
char mat[][]=new char[r][c];
int k=0;
String plainText="";
for(int i=0;i< r;i++)
{
for(int j=0;j< c;j++)
{
mat[i][j]=cipherText.charAt(k++);
}
}
for(int i=0;i< c;i++)
{
for(int j=0;j< r;j++)
{
plainText+=mat[j][i];
}
}
return plainText; }
}
class RailFence
{
public static void main(String args[])throws Exception
{
RailFenceBasic rf=new RailFenceBasic();
Scanner scn=new Scanner(System.in);
int depth;
String plainText,cipherText,decryptedText;
System.out.println("Enter plain text:");
plainText=scn.nextLine();
System.out.println("Enter depth for Encryption:");
depth=scn.nextInt();
cipherText=rf.Encryption(plainText,depth);
System.out.println("Encrypted text is:\n"+cipherText);
decryptedText=rf.Decryption(cipherText, depth);
System.out.println("Decrypted text is:\n"+decryptedText);
}
}
OUTPUT
Enter plain text:
railfencecipher
Enter depth for Encryption:
3
Encrypted text is:
rlnchafcieieepr
Decrypted text is:
railfencecipher
//Program for Implementing Columnar Cipher Transposition In Java:
import java.io.*;
public class columnar
{
` char arr[][],encrypt[][],decrypt[][],keya[],keytemp[];
public void creatematrixE(String s,String key,int row,int column)
{
arr=new char[row][column];
int k=0;
keya=key.toCharArray();
for(int i=0;i<row;i++)
{
for(int j=0;j<column;j++)
{
if(k<s.length())
{
arr[i][j]=s.charAt(k);
k++;
}
else
{
arr[i][j]=' ';
}
}
}
}
public void createkey(String key,int column)
{
keytemp=key.toCharArray();
for(int i=0;i<column-1;i++)
{
for(int j=i+1;j<column;j++)
{
if(keytemp[i]>keytemp[j])
{
char temp=keytemp[i];
keytemp[i]=keytemp[j];
keytemp[j]=temp;
}
}
}
}
public void creatematrixD(String s,String key,int row,int column)
{
arr=new char[row][column];
int k=0;
keya=key.toCharArray();
for(int i=0;i<column;i++)
{
for(int j=0;j<row;j++)
{
if(k<s.length())
{
arr[j][i]=s.charAt(k);
k++;
}
else
{
arr[j][i]=' ';
}
}
}
}
public void encrypt(int row,int column)
{
encrypt=new char[row][column];
for(int i=0;i<column;i++)
{
for(int j=0;j<column;j++)
{
if(keya[i]==keytemp[j])
{
for(int k=0;k<row;k++)
{
encrypt[k][j]=arr[k][i];
}
keytemp[j]='?';
break;
}
}
}
}
public void decrypt(int row,int column)
{
decrypt=new char[row][column];
for(int i=0;i<column;i++)
{
for(int j=0;j<column;j++)
{
if(keya[j]==keytemp[i])
{
for(int k=0;k<row;k++)
{
decrypt[k][j]=arr[k][i];
}
keya[j]='?';
break;
}
}
}
}
public void resultE(int row,int column,char arr[][])
{
System.out.println("Result:");
for(int i=0;i<column;i++)
{
for(int j=0;j<row;j++)
{
System.out.print(arr[j][i]);
}
}
}
public void resultD(int row,int column,char arr[][])
{
System.out.println("Result:");
for(int i=0;i<row;i++)
{
for(int j=0;j<column;j++)
{
System.out.print(arr[i][j]);
}
}
}
public static void main(String args[])throws IOException
{
int row,column,choice;
columnar obj=new columnar();
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Menu:\n1) Encryption\n2) Decryption");
choice=Integer.parseInt(in.readLine());
System.out.println("Enter the string:");
String s=in.readLine();
System.out.println("Enter the key:");
String key=in.readLine();
row=s.length()/key.length();
if(s.length()%key.length()!=0)
row++;
column=key.length();
switch(choice)
{
case 1: obj.creatematrixE(s,key,row,column);
obj.createkey(key,column);
obj.encrypt(row,column);
obj.resultE(row,column,obj.encrypt);
break;
case 2: obj.creatematrixD(s,key,row,column);
obj.createkey(key,column);
obj.decrypt(row,column);
obj.resultD(row,column,obj.decrypt);
break;
}
}
}
//Program for implementing Diff hellman alogorithm
public static void createKey()throws Exception
{
KeyPairGenerator kpg = KeyPairGenerator.getInstance("DiffieHellman");
kpg.initialize(512);
KeyPair kp = kpg.generateKeyPair();
KeyFactory kfactory = KeyFactory.getInstance("DiffieHellman");
DHPublicKeySpec kspec = (DHPublicKeySpec) kfactory.getKeySpec(kp.getPublic(), DHPublicKeySpec.class);
}
public static void createSpecificKey(BigInteger p,BigInteger g)throws Exception
{
KeyPairGenerator kpg = KeyPairGenerator.getInstance("DiffieHellman");
DHParameterSpec param = new DHParameterSpec(p,g);
kpg.initialize(param);
KeyPair kp = kpg.generateKeyPair();
KeyFactory kfactory = KeyFactory.getInstance("DiffieHellman");
DHPublicKeySpec kspec = (DHPublicKeySpec) kfactory.getKeySpec(kp.getPublic(), DHPublicKeySpec.class);
}
static boolean isPrime(long n)
{
if (n%2 == 0)
{
return false;
}
for(int i = 3 ; i*i<=n;i+=2)
{
if(n%i==0)
return false;
}
return true;
}
public static void main(String [] args) throws Exception
{
Random randomGenerator = new Random();
long pValue = randomGenerator.nextInt(1000000);
long gValue = randomGenerator.nextInt(100000);
long correctPValue;
boolean checkPrime = isPrime(pValue);
System.out.println("the number generated is "+pValue);
System.out.println(checkPrime);
while(checkPrime == false)
{
long pValue2 = randomGenerator.nextInt(1000000);
boolean checkPrimeInLoop = isPrime(pValue2);
//System.out.println("value in loop is "+pValue2);
if(checkPrimeInLoop == true)
{
pValue=pValue2;
break;
}
}
long checkSP = (pValue*2)+1;
boolean checkSafePrime = isPrime(checkSP);
//System.out.println(checkSafePrime);
while(checkSafePrime==false)
{
long pValue3=randomGenerator.nextInt(1000000);
boolean checkPrimeInLoop = isPrime(pValue3);
long pValue5=(pValue3*2)+1;
//boolean checkSafePrimeInLoop = isPrime(pValue4);
boolean checkSafePrime2InLoop = isPrime(pValue5);
if(checkSafePrime2InLoop == true && checkPrimeInLoop == true)
{
pValue=pValue3;
break;
}
}
System.out.println("the safe prime is"+pValue);//safe prime
while(gValue>pValue)
{
long gValue2=randomGenerator.nextInt(100000);
if(gValue2<pValue)
{
gValue=gValue2;
break;
}
}
long getDivisor = (pValue-1)/2;
BigInteger bi1,bi2,bi3,bi4;
bi1=BigInteger.valueOf(getDivisor);
bi2 = BigInteger.valueOf(pValue);
bi3 = BigInteger.valueOf(gValue);
bi4= bi3.modPow(bi1,bi2);
long calculatedValue = bi4.longValue();
while(calculatedValue == 1)
{
long gValue3=randomGenerator.nextInt(100000);
long getDivisorInLoop = (pValue-1)/2;
BigInteger bi5,bi6,bi7,bi8;
bi5=BigInteger.valueOf(getDivisorInLoop);
bi6 = BigInteger.valueOf(pValue);
bi7 = BigInteger.valueOf(gValue3);
bi8= bi7.modPow(bi5,bi6);
long calculatedValueInLoop = bi8.longValue();
System.out.println(calculatedValueInLoop);
if(calculatedValueInLoop!=1)
{
gValue=gValue3;
break;
}
}
BigInteger generatorValue,primeValue;
generatorValue = BigInteger.valueOf(gValue);
primeValue = BigInteger.valueOf(pValue);
createKey();
int bitLength=512;
createSpecificKey(generatorValue,primeValue);
// Program for Implementing RC4 Alogorithm
import java.io.*;class rc4{public static void main(String args[])throws IOException{int temp=0;String ptext;String key;int s[]=new int[256];int k[]=new int[256];DataInputStream in=new DataInputStream(System.in);System.out.print("\nENTER PLAIN TEXT\t");ptext=in.readLine();System.out.print("\n\nENTER KEY TEXT\t\t");key=in.readLine();char ptextc[]=ptext.toCharArray();char keyc[]=key.toCharArray();int cipher[]=new int[ptext.length()];int decrypt[]=new int[ptext.length()];
int ptexti[]=new int[ptext.length()];int keyi[]=new int[key.length()];for(int i=0;i<ptext.length();i++){ptexti[i]=(int)ptextc[i];}for(int i=0;i<key.length();i++){keyi[i]=(int)keyc[i];}for(int i=0;i<255;i++){s[i]=i;k[i]=keyi[i%key.length()];}int j=0;for(int i=0;i<255;i++){j=(j+s[i]+k[i])%256;temp=s[i];
s[i]=s[j];s[j]=temp;}int i=0;j=0;int z=0;for(int l=0;l<ptext.length();l++){i=(l+1)%256;j=(j+s[i])%256;temp=s[i];s[i]=s[j];s[j]=temp;z=s[(s[i]+s[j])%256];cipher[l]=z^ptexti[l];decrypt[l]=z^cipher[l];}System.out.print("\n\nENCRYPTED:\t\t");display(cipher);System.out.print("\n\nDECRYPTED:\t\t");display(decrypt);}
static void display(int disp[]){char convert[]=new char[disp.length];for(int l=0;l<disp.length;l++){convert[l]=(char)disp[l];System.out.print(convert[l]);}}}
Out Put
RC4 encryption algorithm Program Output :
ENTER PLAIN TEXT RC4 PROGRAM
ENTER KEY TEXT A
ENCRYPTED: ??-??±?µFJ|
DECRYPTED: RC4 PROGRAM
// Program for Implementing RC5 Alogorithm
mport javax.swing.*;import java.util.io.*;public class Rc5{private int[] s;private int[] l;private int b, u, t, c;private byte[] key;private int rounds;public Rc5(){String str = "tallwalkers";key = GetKeyFromString(str);rounds = 16;b = (int)key.length;u = 4;t = (int)(34);c = 12 / u;s = new int[34];l = new int[12];GenerateKey(key, rounds);}
public Rc5(String password, int round){key = GetKeyFromString(password);rounds = round;b = (int)key.length;u = 4;t = (int)(2 * rounds + 2);c = Math.max(b, 1) / u;s = new int[2 * rounds + 2];l = new int[key.length];GenerateKey(key, rounds);}
public Rc5(byte[] password, int round){
rounds = round;key = password;b = (int)password.length;u = 4;t = (int)(2 * rounds + 2);c = Math.max(b, 1) / u;s = new int[2 * rounds + 2];l = new int[password.length];GenerateKey(key, rounds);}
private int leftRotate(int x, int offset){int t1, t2;t1 = x >> (32 - offset);t2 = x << offset;return t1 | t2;}private int RightRotate(int x, int offset){int t1, t2;t1 = x << (32 - offset);t2 = x >> offset;return t1 | t2;}private void Encode(RefObject<Integer> r1, RefObject<Integer> r2, int rounds){r1.argvalue = r1.argvalue + s[0];r2.argvalue = r2.argvalue + s[1];for (int i = 1; i <= rounds; i++){r1.argvalue = leftRotate(r1.argvalue ^ r2.argvalue, (int)r2.argvalue) + s[2 * i];r2.argvalue = leftRotate(r2.argvalue ^ r1.argvalue, (int)r1.argvalue) + s[2 * i + 1];}}private void Decode(RefObject<Integer> r1, RefObject<Integer> r2, int rounds){for (int i = rounds; i >= 1; i--){r2.argvalue = (RightRotate(r2.argvalue - s[2 * i + 1], (int)r1.argvalue)) ^ r1.argvalue;r1.argvalue = (RightRotate(r1.argvalue - s[2 * i], (int)r2.argvalue)) ^ r2.argvalue;}
r2.argvalue = r2.argvalue - s[1];r1.argvalue = r1.argvalue - s[0];}
private void GenerateKey(byte[] key, int rounds){int P32 = Integer.parseInt("b7e15163", System.Globalization.NumberStyles.HexNumber);int Q32 = Integer.parseInt("9e3779b9", System.Globalization.NumberStyles.HexNumber);for (int i = key.length - 1; i >= 0; i--){l[i] = leftRotate((int)i, 8) + key[i];}s[0] = P32;for (int i = 1; i <= t - 1; i++){s[i] = s[i - 1] + Q32;}int ii, jj;ii = jj = 0;int x, y;x = y = 0;int v = 3 * Math.max(t, c);for (int counter = 0; counter <= v; counter++){x = s[ii] = leftRotate((s[ii] + x + y), 3);y = l[jj] = leftRotate((l[jj] + x + y), (int)(x + y));ii = (ii + 1) % t;jj = (jj + 1) % c;}}private byte[] GetKeyFromString(String str){char[] mykeyinchar = str.toCharArray();byte[] mykeyinbytes = new byte[mykeyinchar.length];for (int i = 0; i < mykeyinchar.length; i++){mykeyinbytes[i] = (byte)mykeyinchar[i];}return mykeyinbytes;}
public final void Encrypt(FileStream streamreader, FileStream streamwriter)
{int r1, r2;System.IO.BinaryReader br = new System.IO.BinaryReader(streamreader);System.IO.BinaryWriter bw = new System.IO.BinaryWriter(streamwriter);long filelength = streamreader.getLength();while (filelength > 0){try{r1 = br.ReadUInt32();try{r2 = br.ReadUInt32();}catch (java.lang.Exception e){r2 = 0;}}catch (java.lang.Exception e2){r1 = r2 = 0;}
RefObject<Integer> tempRefObject = new RefObject<Integer>(r1);RefObject<Integer> tempRefObject2 = new RefObject<Integer>(r2);Encode(tempRefObject, tempRefObject2, rounds);r1 = tempRefObject.argvalue;r2 = tempRefObject2.argvalue;bw.Write(r1);bw.Write(r2);filelength -= 8;}streamreader.close();streamwriter.close();}public final void Decrypt(FileStream streamreader, FileStream streamwriter){int r1, r2;System.IO.BinaryReader br = new System.IO.BinaryReader(streamreader);System.IO.BinaryWriter bw = new System.IO.BinaryWriter(streamwriter);long filelength = streamreader.getLength();
while (filelength > 0){try{r1 = br.ReadUInt32();r2 = br.ReadUInt32();RefObject<Integer> tempRefObject = new RefObject<Integer>(r1);RefObject<Integer> tempRefObject2 = new RefObject<Integer>(r2);Decode(tempRefObject, tempRefObject2, rounds);r1 = tempRefObject.argvalue;r2 = tempRefObject2.argvalue;if (!(r1 == 0 && r2 == 0 && (filelength - 8 <= 0))){bw.Write(r1);bw.Write(r2);}if (r2 == 0 && (filelength - 8 <= 0)){bw.Write(r1);}filelength -= 8;}catch (java.lang.Exception e){JOptionPane.showConfirmDialog(null, "May be U try to decrypt an normal file (plain file)", "Error",
JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);return;}}streamreader.close();streamwriter.close();}
}
// Program for RSA public key encryption algorithm implementation.
import java.math.BigInteger;
import java.security.SecureRandom;
public class RSA {
private BigInteger n, d, e;
private int bitlen = 1024;
/** Create an instance that can encrypt using someone elses public key. */
public RSA(BigInteger newn, BigInteger newe) {
n = newn;
e = newe;
}
/** Create an instance that can both encrypt and decrypt. */
public RSA(int bits) {
bitlen = bits;
SecureRandom r = new SecureRandom();
BigInteger p = new BigInteger(bitlen / 2, 100, r);
BigInteger q = new BigInteger(bitlen / 2, 100, r);
n = p.multiply(q);
BigInteger m = (p.subtract(BigInteger.ONE)).multiply(q
.subtract(BigInteger.ONE));
e = new BigInteger("3");
while (m.gcd(e).intValue() > 1) {
e = e.add(new BigInteger("2"));
}
d = e.modInverse(m);
}
/** Encrypt the given plaintext message. */
public synchronized String encrypt(String message) {
return (new BigInteger(message.getBytes())).modPow(e, n).toString();
}
/** Encrypt the given plaintext message. */
public synchronized BigInteger encrypt(BigInteger message) {
return message.modPow(e, n);
}
/** Decrypt the given ciphertext message. */
public synchronized String decrypt(String message) {
return new String((new BigInteger(message)).modPow(d, n).toByteArray());
}
/** Decrypt the given ciphertext message. */
public synchronized BigInteger decrypt(BigInteger message) {
return message.modPow(d, n);
}
/** Generate a new public and private key set. */
public synchronized void generateKeys() {
SecureRandom r = new SecureRandom();
BigInteger p = new BigInteger(bitlen / 2, 100, r);
BigInteger q = new BigInteger(bitlen / 2, 100, r);
n = p.multiply(q);
BigInteger m = (p.subtract(BigInteger.ONE)).multiply(q
.subtract(BigInteger.ONE));
e = new BigInteger("3");
while (m.gcd(e).intValue() > 1) {
e = e.add(new BigInteger("2"));
}
d = e.modInverse(m);
}
/** Return the modulus. */
public synchronized BigInteger getN() {
return n;
}
/** Return the public key. */
public synchronized BigInteger getE() {
return e;
}
/** Trivial test program. */
public static void main(String[] args) {
RSA rsa = new RSA(1024);
String text1 = "Yellow and Black Border Collies";
System.out.println("Plaintext: " + text1);
BigInteger plaintext = new BigInteger(text1.getBytes());
BigInteger ciphertext = rsa.encrypt(plaintext);
System.out.println("Ciphertext: " + ciphertext);
plaintext = rsa.decrypt(ciphertext);
String text2 = new String(plaintext.toByteArray());
System.out.println("Plaintext: " + text2);
}
}
//Write a program to encrypt input string by using Blowfish algorithm
//Blowfish algorithm
// Example program for Blowfish algorithm in java
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.swing.JOptionPane;
public class BlowfishCipher {
public static void main(String[] args) throws Exception {
KeyGenerator keygen = KeyGenerator.getInstance("Blowfish");
// create a key
SecretKey secretkey = keygen.generateKey();
Cipher cip = Cipher.getInstance("Blowfish");
// initialise cipher to with secret key
cip.init(Cipher.ENCRYPT_MODE, secretkey);
String inputText = JOptionPane.showInputDialog(" Give Input: ");
byte[] encrypted = cip.doFinal(inputText.getBytes());
cip.init(Cipher.DECRYPT_MODE, secretkey);
byte[] decrypted = cip.doFinal(encrypted);
JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
"encrypted : " + new String(encrypted) + "\n" +
"decrypted : " + new String(decrypted));
System.exit(0);
}
}