You are on page 1of 27

1.

a) Ceasar Cipher

import java.util.Scanner;
public class Caesar {

public static void main(String[] args){


String cip=Caesar.encrypt();
Caesar.decrypt(cip);
}
// Caesar Encryption Function
private static String encrypt() {
char chars[] =
{'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
String empty = "empty";
Scanner input = new Scanner(System.in);
System.out.println("Enter the plaintext");
String plainText = input.nextLine();
String cipher = null;
char[] plain = plainText.toCharArray();

for(int i = 0;i<plain.length;i++){
for(int j = 0 ; j<=25;j++){
if(j<=22){
if(plain[i]==chars[j]){
plain[i] = chars[j+3];
break;
}
}//End nested If
else if(plain[i] == chars[j])
{
plain[i] = chars [j-23];
} //End else
} //End nested for loop
} //End of For loop
cipher = String.valueOf(plain);
System.out.println(" cipher text is "+cipher);
Scanner in = new Scanner(System.in);
System.out.println("To Decrypt plaintext enter 1");
int choice = in.nextInt();
if(choice == 1){
return cipher;
}
else{
System.out.println("Thank you");}
return empty;
}

// Caesar Decryption Function


private static String decrypt(String cip) {
char chars[] =
{'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
String cipher = null;
String empty = "empty";
char[] cipher1 = cip.toCharArray();
if(cip .equals(empty)){
System.out.println(" No text is Decrypted");
}
else{ //char[] cipher1 = cip.toCharArray();
for(int i = 0;i<cipher1.length;i++){
for(int j = 0 ; j<=25;j++){
if(j>=3 && cipher1[i]==chars[j]){
cipher1[i] = chars[j-3];
break;
}
if(cipher1[i] == chars[j] && j<3){
cipher1[i] = chars[23+j];
break;
} //End IF
} //End nested for loop
} //End of For loop
}
cipher=String.valueOf(cipher1);
System.out.println(" Plain text is '"+cipher+"'");
return cipher;
}
}

1.b) Modified Ceasar cipher


import java.io.*;
public class modicaesarcipher
{
public String encrypt(int shift, String line)
{
String result="";
int offset;
for(int i=0;i<line.length();i++)
{
offset=((int)line.charAt(i)+shift)%256;
result+=(char)(offset);
}
return result;
}
public String decrypt(int shift, String line)
{
String result="";
int offset;
for(int i=0;i<line.length();i++)
{
offset=((int)line.charAt(i)-shift)%256;
if(offset<0)
offset+=256;
result+=(char)(offset);
}
return result;
}
public static void main(String args[])throws IOException
{
modicaesarcipher obj=new modicaesarcipher();
BufferedReader in=new BufferedReader(new
InputStreamReader(System.in));
int choice;
System.out.println("Menu:\n1: Encryption\n2: Decryption");
choice=Integer.parseInt(in.readLine());
System.out.println("Enter the shift: ");
int shift=Integer.parseInt(in.readLine());
System.out.println("Enter the line: ");
String line=in.readLine();
System.out.println("Result:");
switch(choice)
{
case 1:System.out.println(obj.encrypt(shift,line));
break;
case 2:System.out.println(obj.decrypt(shift,line));
break;
default:
System.out.println("Invalid input!");
break;
}
}
}

1.c) Mono Alphabetic Cipher


import java.util.Scanner;
import java.io.*;
class MonoalphabeticCipher
{
static String c1="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static String c2="LMNOPQRSTUVWXYZACEBFDGHIJK";
public static void main(String[] args)
{
char current;
String ciphertxt="";
String plaintxt,str2;
int key, indx=0,len;
Scanner in1=new Scanner(System.in);
Scanner in =new Scanner(System.in);
System.out.println("\n SUBSTITUTION CIPHER ALGORITHM FOR
ENCRYPTION");
System.out.println("Enter the message to be Encrypted:");
plaintxt=in1.nextLine();
plaintxt=plaintxt.toUpperCase();
len=plaintxt.length();
for(int i=0;i<len;i++)
{
current=plaintxt.charAt(i);
for(int j=0;j<26;j++)
{
if(c1.charAt(j)==current)
indx=j;
}
ciphertxt=ciphertxt+c2.charAt(indx);
}
System.out.println("The Ciphertext is:"+ciphertxt);
System.out.print("\nDo you want to Decrypt the message(Type 'Yes' or
'No')");
String choice=(System.console()).readLine();
plaintxt=" ";
if(choice.equalsIgnoreCase("yes")==true)
{
for(int i=0; i<ciphertxt.length();i++)
{
current=ciphertxt.charAt(i);
for(int j=0;j<26;j++)
{
if(c2.charAt(j)==current)
indx=j;
}
plaintxt=plaintxt+c1.charAt(indx);
}
System.out.print("The PlainText is:"+plaintxt.toLowerCase());
}
else
System.exit(0);
}
}
1.d) Poly Alphabetic cipher (Vigenere Cipher)
import java.util.*;
public class Viginere
{
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
String p="",c="",k="",l="abcdefghijklmnopqrstuvwxyz";
System.out.print("give the pl text ");
p=in.nextLine();
System.out.print("give the key ");
k=in.nextLine();
int klen=k.length();
int plen=p.length();
String y =k;
int m = plen%klen;
for( int i=1; i<plen/klen ; i++)
{
k=k+y;
}
k=k+k.substring(0,m);
for (int j=0; j<plen; j++ )
{
c=c + l.charAt((l.indexOf(k.charAt(j)) + l.indexOf(p.charAt(j)))%26);
}
c=c.toUpperCase();
System.out.println("Ciphertext "+c);
// Decryption
c = c.toLowerCase();
String pl = "";
for (int r=0; r<plen; r++)
{
pl=pl + l.charAt(((l.indexOf(c.charAt(r)) - l.indexOf(k.charAt(r))) +26
)%26);
}
System.out.println("decipher: "+p); } }
2.a) Rail fence Cipher
public class railfence {
public static void main(String args[])
{
String input = "inputstring";
String output = "";
int len = input.length();
System.out.println("Input String : " + input);
for(int i=0;i<len;i+=2) {
output += input.charAt(i);
}
for(int i=1;i<len;i+=2) {
output += input.charAt(i);
}
System.out.println("Ciphered Text : "+output);
}
}

2.b) Simple Columnar Cipher

import java.io.*;
import java.math.*;
class SimpleColumner
{
public static void main(String[] args)
{
String pt,ct;
int key;
char matrix[][];
Console c=System.console();
System.out.println("Its simple Columnar Technique.");
pt=c.readLine("Enter the message to be encrypted\n");
int len=pt.length();
int rows;
if(len%6==0)
rows=len/6;
else
rows=(len/6)+1;
matrix=new char[rows][6];
int count=0;
key=Integer.parseInt(c.readLine("Enter the key for encryption : "));
for(int i=0;i<rows;i++)
{
for(int j=0;j<6;j++)
{
if(count<len)
matrix[i][j]=pt.charAt(count);
else
matrix[i][j]='$';
count++;
}
}
ct="";
int mul=100000;
int num=key;
for(int i=0;i<6;i++)
{
int r=num/mul;
num=num%mul;
mul=mul/10;
for(int j=0;j<rows;j++)
ct=ct+matrix[j][r-1];
}
System.out.println("The cipher text is: "+ct);
String choice=c.readLine("\nDo you want to Decrypt the cipher text: ");
pt="";
if(choice.equalsIgnoreCase("yes")==true)
{
for(int i=0;i<rows;i++)
{
for(int j=0;j<6;j++)
if(matrix[i][j]!='$')
pt=pt+matrix[i][j];
}
System.out.println("The Decrypted message id: "+pt);
}
else
System.exit(0);
}
}
2.c) Multi Columnar Cipher

import java.io.*;
import java.math.*;
class MultiColumnar
{
String pt,ct;
int key;
char matrix1[][][], matrix2[][][];
int round,rows,count=0,len,mul,num;
Console c=System.console();
public void encrypt()
{
pt=c.readLine("Enter the message to be encrypted\n");
round=Integer.parseInt(c.readLine("Enter the number of iterations
: "));
len=pt.length();
if(len%6==0)
rows=len/6;
else
rows=(len/6)+1;
matrix1=new char[round][rows][6];
key=Integer.parseInt(c.readLine("Enter the key for encryption : "));
for(int k=0;k<round;k++)
{
count=0;
for(int i=0;i<rows;i++)
{
for(int j=0;j<6;j++)
{
if(count<len)
matrix1[k][i][j]=pt.charAt(count);
else
matrix1[k][i][j]='$';
count++;
}
}
ct="";
mul=100000;
num=key;
for(int i=0;i<6;i++)
{
int r=num/mul;
num=num%mul;
mul=mul/10;
for(int j=0;j<rows;j++)
ct=ct+matrix1[k][j][r-1];
}
pt=ct;
len=pt.length();
}
System.out.println("The cipher text is: "+ct);
}

public void decrypt()


{
rows=len/6;
matrix2=new char[round][rows][6];

for(int k=0;k<round;k++)
{
pt="";
len=ct.length();
count=0;
num=key;
mul=100000;
do
{
int r=num/mul;
num=num%mul;
mul=mul/10;
for(int j=0;j<rows;j++)
{
matrix2[k][j][r-1]=ct.charAt(count);
count++;
}
}
while(num>0);
for(int i=0;i<rows;i++)
{
for(int j=0;j<6;j++)
{
if(k==round-1)
{
if(matrix2[k][i][j]!='$')
pt=pt+matrix2[k][i][j];
}
else
pt=pt+matrix2[k][i][j];
}
}
ct=pt;
}
System.out.println("The plain text is: "+pt);
}
public static void main(String[] args)
{
System.out.println("Multi Columnar Transposition Technique: ");
MultiColumnar mc=new MultiColumnar();
mc.encrypt();
Console c=System.console();
String choice=c.readLine("\n Do ypu want to Decrypt the cpher text: ");
if(choice.equalsIgnoreCase("yes")==true)
{
mc.decrypt();
}
else
System.exit(0);
}}
2.d) Vernam Cipher
import java.lang.Math;
public class Vernam {
public static void main(String args[]) {
String text = new String("hello");
char[] arText = text.toCharArray();
String cipher = new String("XYZHG");
char[] arCipher = cipher.toCharArray();
char[] encoded = new char[5];
System.out.println("Encoded " + text + " to be... ");
for (int i = 0; i < arText.length; i++) {
encoded[i] = (char) (arText[i] ^ arCipher[i]);
System.out.print(encoded[i]);
}
System.out.println("\nDecoded to be... ");
for (int i = 0; i < encoded.length; i++) {
char temp = (char) (encoded[i] ^ arCipher[i]);
System.out.print(temp);
}}}

3) Diffie Hellman Key Exchange Algorithm

import java.io.*;
import java.util.*;
import java.util.Scanner;
class Diffie
{
public static void main( String [] args)

{
Scanner sc = new Scanner (System.in);
int g,n,x,y;
System.out.println("enter value of n");
n=sc.nextInt();
System.out.println("enter value of g");
g=sc.nextInt();
System.out.println("enter value of x");
x=sc.nextInt();
System.out.println("enter value of y");
y=sc.nextInt();

double a=(Math.pow(g,x)) %n;


System.out.println("Value of a =" + a);

double b=(Math.pow(g,y)) %n;


System.out.println("Value of b =" + b);

double k1=(Math.pow(b,x)) %n;


System.out.println("Value of k1 =" + k1);

double k2=(Math.pow(a,y)) %n;


System.out.println("Value of k2 =" + k2);
if(k1==k2)
System.out.println("Both are same");
else
System.out.println("Both are not same");
} // end main
} //end class

4.Implementation of DES algorithm

import javax.crypto.*;
import java.io.*;
import java.security.InvalidAlgorithmParameterException;
import java.security.spec.*;
import javax.crypto.spec.IvParameterSpec;
import java.lang.*;
public class DES
{
Cipher ec;
Cipher dc;
DES( SecretKey key)
{
try
{
ec = Cipher.getInstance("DES");
dc = Cipher.getInstance("DES");
ec.init(Cipher.ENCRYPT_MODE, key);
dc.init(Cipher.DECRYPT_MODE, key);
}
catch( Exception e){ }
}
public String encrypt(String str)
{
try
{
// Encode the string into bytes using utf8
byte[] utf8 = str.getBytes("UTF8");
// Encrypt
byte[] enc = ec.doFinal(utf8);
// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
}
catch(Exception e) { }
return null;
}
public String decrypt(String str)
{
try
{
// Decode base64 to get bytes
byte[] dec=new sun.misc.BASE64Decoder().decodeBuffer(str);
// Decrypt
byte[] utf8 = dc.doFinal(dec);
// Decode using utf-8
return new String(utf8, "UTF8");
}
catch(Exception e) {}
return null;
}
public static void main(String [] args)
{
SecretKey key=null;
try
{
// Generate a DES key
KeyGenerator keyGen = KeyGenerator.getInstance("DES");
key = keyGen.generateKey();
DES desenc = new DES(key);
String s = "Welcome to our college....";
String en = desenc.encrypt(s);
String de = desenc.decrypt(en);
System.out.println("Original Text:" +s);
System.out.println("Encrypted Text:" +en);
System.out.println("Decrypted Text:" +de);
}
catch (Exception e) {}
}// end main
} //end class

5) Implementation of AES algorithm

import java.security.*;
import javax.crypto.*;
import java.io.*;
public class AES
{
Cipher ecipher;
Cipher dcipher;
AES(SecretKey key)
{
try
{
ecipher = Cipher.getInstance("AES");
dcipher = Cipher.getInstance("AES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);
}
catch (Exception e) {}
}
public String encrypt(String str)
{
try
{
// Encode the string into bytes using utf8
byte[] utf8 = str.getBytes("UTF8");
// Encrypt
byte[] enc = ecipher.doFinal(utf8);
// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
}
catch(Exception e) {}
return null;
}
public String decrypt(String str)
{
try
{
// Decode base64 to get bytes
byte[] dec=new sun.misc.BASE64Decoder().decodeBuffer(str);
// Decrypt
byte[] utf8 = dcipher.doFinal(dec);
// Decode using utf-8
return new String(utf8, "UTF8");
}
catch(Exception e) {}
return null;
}
public static void main(String args[])
{
SecretKey key=null;
try
{
// Generate a AES key
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
key = keyGen.generateKey();
}
catch (Exception e)
{
e.printStackTrace();
}
AES dese = new AES(key);
String o = "Welcome to our college....";
String en = dese.encrypt(o);
String de = dese.decrypt(en);
System.out.println("Original Text:"+o);
System.out.println("Encrypted Text:"+en);
System.out.println("Decrypted Text:"+de);
}
}

6) Implementation of RSA algorithm

import java.math.*;
import java.security.*;
public class RSA
{
BigInteger p,q,n,d,e,ph,t;
SecureRandom r;
public RSA()
{
r=new SecureRandom();
p=new BigInteger(512,100,r); // Prime nos.
q=new BigInteger(512,100,r);
System.out.println("prime nos p and q are "+p.intValue()+" ,
"+q.intValue());
n=p.multiply(q); // n=p*q
ph=(p.subtract(new BigInteger("1"))); // -----ph=(p-1)
ph=ph.multiply(q.subtract(new BigInteger("1"))); // ------ ph=ph * (q-1)
e=new BigInteger("2");//initial factor
while(ph.gcd(e).intValue() > 1 || e.compareTo(ph) !=-1) // checks factors
encryption key e not as the factors of ph
e = e.add(new BigInteger("1"));//or "2" when bug
d=e.modInverse(ph); // select d private or decryption key such that (d*e)
mod (p-1)*(q-1) = 1
System.out.println("public key is ("+n.intValue()+" , "+e.intValue()+")");
System.out.println("pvt key is ("+n.intValue()+" , " +d.intValue()+")");
BigInteger msg= new BigInteger("15"); // original msg
System.out.println("\nMessage is: "+msg);
BigInteger enmsg=encrypt(msg,e,n);
System.out.println("\nEncrypted msg is: "+enmsg.intValue());
BigInteger demsg=decrypt(enmsg,d,n);
System.out.println("\nDecrypted msg is: "+demsg.intValue());
}
BigInteger encrypt(BigInteger msg,BigInteger e,BigInteger n)
{
return msg.modPow(e, n); //PT raised to e mod n
}
BigInteger decrypt(BigInteger msg,BigInteger d,BigInteger n)
{
return msg.modPow(d, n); //CT raised to d mod n
}
public static void main(String[] args)
{
new RSA();
}
}

7) Implementation of Rc4 Algorithm

class RC4Demo
{
String strPlainText;
static char cipher[];
RC4Demo(String strPlainText,int []key)
{
this.strPlainText = strPlainText;
int S[] = new int[255];
cipher = new char[strPlainText.length()];
for (int i=0;i<S.length;i++)
{
S[i] = i;
}
int i=0;
int j=0;
for (int k=0;k < strPlainText.length();k++)
{
int modk = (k%key.length);
int Kc = key[modk];
j = (S[i] + j + Kc) % 256 + 1;
int temp = S[i];
S[i] = S[j];
S[j] = temp;
int Sc = (S[i]+S[j]) % 256;
int Ck = S[Sc];
cipher[k] = (char) (Ck ^ (int)strPlainText.charAt(k));
i = i+1;
}
}
public static void main(String[] args)
{
int K[] = {1, 2, 3, 4, 5};
String strOriginal = "Hello World";
System.out.println("Original String--> "+strOriginal);
new RC4Demo(strOriginal,K);
for (int i=0;i<cipher.length;i++)
{
System.out.print(" "+cipher[i]);
}}}

8) Implementation of Blowfish Algorithm

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);
}
}

You might also like