LAB ASSIGNMENT With Output

Download as pdf or txt
Download as pdf or txt
You are on page 1of 53

KUPPUSAMY.

S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB
LAB ASSIGNMENT – I
TCP ONE WAY COMMUNICATION

CLIENT SIDE
import java.net.*;
import java.io.*;
class MyClient
{
public static void main(String args[])throws IOException
{
Socket s=new Socket("localHost",8000);
DataInputStream in=new DataInputStream(s.getInputStream());
while(true)
{
String str=in.readLine();
System.out.println("Message Received:"+str);
if(str.equals("end}};
{
s.close();
break;
}
}
}
}

1
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB

SERVER SIDE
import java.net.*;
import java.io.*;
class MyServer
{
public static void main(String a[])throws IOException
{
ServerSocket ss=new ServerSocket(8000);
Socket s=ss.accept();
DataInputStream in=new DataInputStream(System.in);
PrintStream dos=new PrintStream(s.getOutputStream());
while(true)
{
System.out.println("enter message to send:");
String str=in.readLine();
dos.println(str);
if(str.equals("end"))
{
ss.close();
break;
}
}
}
}

2
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB

OUTPUT

3
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB

TCP TWO WAY COMMUNICATION

CLIENT SIDE
import java.net.*;
import java.io.*;
public class MyClient {
public static void main(String[] args) throws IOException{
Socket s = new Socket("localhost",3333);
DataInputStream din= new DataInputStream(s.getInputStream());
DataOutputStream dout= new
DataOutputStream(s.getOutputStream());
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str="",str2="";
while(!str.equals("stop")){
str=br.readLine();
dout.writeUTF(str);
str2=din.readUTF();
System.out.println("Server Says: "+str2);
}
}
}

4
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB

SERVER SIDE
import java.net.*;
import java.io.*;
public class MyServer{
public static void main(String[] args) throws IOException{
ServerSocket ss = new ServerSocket(3333);
Socket s =ss.accept();
DataInputStream din = new DataInputStream(s.getInputStream());
DataOutputStream dout = new
DataOutputStream(s.getOutputStream());
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str="",str2="";
while(!str.equals("stop")){
str=din.readUTF();
System.out.println("Client Says: "+str);
str2=br.readLine();
dout.writeUTF(str2);
dout.flush();
}
din.close();
ss.close();
}
}

5
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB

OUTPUT

6
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB

MULTICASTING
CLIENT SIDE;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;

public class MulticastSocketClient


{
final static String INET_ADDR = "224.0.0.3";
final static int PORT = 8888;
public static void main(String[] args) throws UnknownHostException
{
InetAddress address = InetAddress.getByName(INET_ADDR);
byte[] buf = new byte[256];
try (MulticastSocket clientSocket = new MulticastSocket(PORT))
{
clientSocket.joinGroup(address);
while (true)
{
DatagramPacket msgPacket = new DatagramPacket(buf, buf.length);
clientSocket.receive(msgPacket);

7
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB
String msg = new String(buf, 0, buf.length);
System.out.println("Socket 1 received msg: " + msg);
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}

SERVER SIDE;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class MulticastSocketServer


{
final static String INET_ADDR = "224.0.0.3";
final static int PORT = 8888;
public static void main(String[] args) throws UnknownHostException,
InterruptedException {
InetAddress addr = InetAddress.getByName(INET_ADDR);

8
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB
try (DatagramSocket serverSocket = new DatagramSocket())
{
for (int i = 0; i < 5; i++)
{
String msg = "Sent message no " + i;
DatagramPacket msgPacket = new DatagramPacket(msg.getBytes(),
msg.getBytes().length, addr, PORT);
serverSocket.send(msgPacket);
System.out.println("Server sent packet with msg: " + msg);
Thread.sleep(500);
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}

9
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB

OUTPUT

10
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB

Caesar Cipher Program

Decryption;
import java.util.*;
public class CaesarCipherProgram
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println(" Input the ciphertext message : ");
String ciphertext = sc.nextLine();
System.out.println(" Enter the shift value : ");
int shift = sc.nextInt();
String decryptMessage = "";
for(int i=0; i < ciphertext.length();i++)
{
char alphabet = ciphertext.charAt(i);
if(alphabet >= 'a' && alphabet <= 'z')
{
alphabet = (char) (alphabet - shift);
if(alphabet < 'a')
{
alphabet = (char) (alphabet-'a'+'z'+1);

11
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB
}
decryptMessage = decryptMessage + alphabet;
}
else if(alphabet >= 'A' && alphabet <= 'Z')
{
alphabet = (char) (alphabet - shift);
if (alphabet < 'A')
{
alphabet = (char) (alphabet-'A'+'Z'+1);
}
decryptMessage = decryptMessage + alphabet;
}
else
{
decryptMessage = decryptMessage + alphabet;
}
}
System.out.println(" decrypt message : " + decryptMessage);
}
}

12
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB

Encryption;
import java.util.*;
public class CaesarCipherProgram
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println(" Input the plaintext message : ");
String plaintext = sc.nextLine();
System.out.println(" Enter the value by which each character in the
plaintext message gets shifted : ");
int shift = sc.nextInt();
String ciphertext = "";
char alphabet;
for(int i=0; i < plaintext.length();i++)
{
alphabet = plaintext.charAt(i);
if(alphabet >= 'a' && alphabet <= 'z')
{
alphabet = (char) (alphabet + shift);
if(alphabet > 'z')
{
alphabet = (char) (alphabet+'a'-'z'-1);

13
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB
}
ciphertext = ciphertext + alphabet;
}
else if(alphabet >= 'A' && alphabet <= 'Z')
{
alphabet = (char) (alphabet + shift);
if(alphabet > 'Z')
{
alphabet = (char) (alphabet+'A'-'Z'-1);
}
ciphertext = ciphertext + alphabet;
}
else
{
ciphertext = ciphertext + alphabet;
}
}
System.out.println(" ciphertext : " + ciphertext);
}
}

14
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB

OUTPUT

15
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB

PLAYFAIR CIPHER
CODE

import java.util.Scanner;
public class Playfair
{
private String KeyWord = new String();
private String Key = new String();
private char matrix_arr[][] = new char[5][5];

public void setKey(String k)


{
String K_adjust = new String();
boolean flag = false;
K_adjust = K_adjust + k.charAt(0);
for (int i = 1; i < k.length(); i++)
{
for (int j = 0; j < K_adjust.length(); j++)
{
if (k.charAt(i) == K_adjust.charAt(j))
{
flag = true;
}

16
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB
}
if (flag == false)
K_adjust = K_adjust + k.charAt(i);
flag = false;
}
KeyWord = K_adjust;
}
public void KeyGen()
{
boolean flag = true;
char current;
Key = KeyWord;
for (int i = 0; i < 26; i++)
{
current = (char) (i + 97);
if (current == 'j')
continue;
for (int j = 0; j < KeyWord.length(); j++)
{
if (current == KeyWord.charAt(j))
{
flag = false;
break;
}
}
17
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB
if (flag)
Key = Key + current;
flag = true;
}
System.out.println(Key);
matrix();
}
private void matrix()
{
int counter = 0;
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
matrix_arr[i][j] = Key.charAt(counter);
System.out.print(matrix_arr[i][j] + " ");
counter++;
}
System.out.println();
}
}
private String format(String old_text)
{
int i = 0;
int len = 0;
18
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB
String text = new String();
len = old_text.length();
for (int tmp = 0; tmp < len; tmp++)
{
if (old_text.charAt(tmp) == 'j')
{
text = text + 'i';
}
else
text = text + old_text.charAt(tmp);
}
len = text.length();
for (i = 0; i < len; i = i + 2)
{
if (text.charAt(i + 1) == text.charAt(i))
{
text = text.substring(0, i + 1) + 'x' + text.substring(i + 1);
}
}
return text;
}
private String[] Divid2Pairs(String new_string)
{
String Original = format(new_string);
int size = Original.length();
19
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB
if (size % 2 != 0)
{
size++;
Original = Original + 'x';
}
String x[] = new String[size / 2];
int counter = 0;
for (int i = 0; i < size / 2; i++)
{
x[i] = Original.substring(counter, counter + 2);
counter = counter + 2;
}
return x;
}
public int[] GetDiminsions(char letter)
{
int[] key = new int[2];
if (letter == 'j')
letter = 'i';
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
if (matrix_arr[i][j] == letter)
{
20
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB
key[0] = i;
key[1] = j;
break;
}
}
}
return key;
}
public String encryptMessage(String Source)
{
String src_arr[] = Divid2Pairs(Source);
String Code = new String();
char one;
char two;
int part1[] = new int[2];
int part2[] = new int[2];
for (int i = 0; i < src_arr.length; i++)
{
one = src_arr[i].charAt(0);
two = src_arr[i].charAt(1);
part1 = GetDiminsions(one);
part2 = GetDiminsions(two);
if (part1[0] == part2[0])
{
if (part1[1] < 4)
21
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB
part1[1]++;
else
part1[1] = 0;
if (part2[1] < 4)
part2[1]++;
else
part2[1] = 0;
}
else if (part1[1] == part2[1])
{
if (part1[0] < 4)
part1[0]++;
else
part1[0] = 0;
if (part2[0] < 4)
part2[0]++;
else
part2[0] = 0;
}
else
{
int temp = part1[1];
part1[1] = part2[1];
part2[1] = temp;
}
22
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB
Code = Code + matrix_arr[part1[0]][part1[1]]
+ matrix_arr[part2[0]][part2[1]];
}
return Code;
}
public String decryptMessage(String Code)
{
String Original = new String();
String src_arr[] = Divid2Pairs(Code);
char one;
char two;
int part1[] = new int[2];
int part2[] = new int[2];
for (int i = 0; i < src_arr.length; i++)
{
one = src_arr[i].charAt(0);
two = src_arr[i].charAt(1);
part1 = GetDiminsions(one);
part2 = GetDiminsions(two);
if (part1[0] == part2[0])
{
if (part1[1] > 0)
part1[1]--;
else
part1[1] = 4;
23
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB
if (part2[1] > 0)
part2[1]--;
else
part2[1] = 4;
}
else if (part1[1] == part2[1])
{
if (part1[0] > 0)
part1[0]--;
else
part1[0] = 4;
if (part2[0] > 0)
part2[0]--;
else
part2[0] = 4;
}
else
{
int temp = part1[1];
part1[1] = part2[1];
part2[1] = temp;
}
Original = Original + matrix_arr[part1[0]][part1[1]]
+ matrix_arr[part2[0]][part2[1]];
}
24
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB
return Original;
}

public static void main(String[] args)


{
PlayfairCipherDecryption x = new PlayfairCipherDecryption();
Scanner sc = new Scanner(System.in);
System.out.println("Enter a keyword:");
String keyword = sc.next();
x.setKey(keyword);
x.KeyGen();
System.out
.println("Enter word to encrypt: (Make sure length of
message is even)");
String key_input = sc.next();
if (key_input.length() % 2 == 0)
{
System.out.println("Encryption: " + x.encryptMessage(key_input));
System.out.println("Decryption: "
+ x.decryptMessage(x.encryptMessage(key_input)));
}
else
{
System.out.println("Message length should be even");
}

25
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB
sc.close();
}
}

OUTPUT

26
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB

HILL CIPHER

SOURCE CODE

import java.util.Scanner;
class HillCipher
{
public String encrypt(String plainText, int key[][])
{
char[] text=plainText.toCharArray();
int c1,c2,c3,p1,p2,p3;
p1=(int)text[0]-65;
p2=(int)text[1]-65;
p3=(int)text[2]-65;
c1=(key[0][0]*p1+key[0][1]*p2+key[0][2]*p3)%26;
c2=(key[1][0]*p1+key[1][1]*p2+key[1][2]*p3)%26;
c3=(key[2][0]*p1+key[2][1]*p2+key[2][2]*p3)%26;
char[] cipherText=new char[3];
cipherText[0]=(char)(c1+65);
cipherText[1]=(char)(c2+65);
cipherText[2]=(char)(c3+65);
return String.valueOf(cipherText);
}
}
27
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB
public class HillCipherDemo
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
HillCipher hillCipher = new HillCipher();
System.out.print("Enter the plaintext message:");
String plainText = sc.nextLine();
int[][] key=new int[3][3];
System.out.println("Enter the Key in 3 X 3 Matrix Format:");
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
key[i][j]= sc.nextInt();
}
}
String cipherText = hillCipher.encrypt(plainText.toUpperCase(),
key);
System.out.println("Cipher Text="+cipherText);
}
}

28
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB

OUTPUT

29
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB

VIGENERE CIPHER

SOURCE CODE

import java.util.Arrays;
import java.util.Scanner;
public class VigenereCipher
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String plainText = sc.nextLine();
String key=sc.nextLine();
char[] plainTextChar = plainText.toUpperCase().toCharArray();
char[] keyChar =
Arrays.copyOf(key.toUpperCase().toCharArray(),plainTextChar.lengt
h);
int i=0;
for(int j=key.toCharArray().length;j<keyChar.length;j++)
{
keyChar[j]=keyChar[i];
i++;
}
char[] cipherTextChar = new char[keyChar.length];

30
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB
for(i=0;i<cipherTextChar.length;i++)
{
cipherTextChar[i]=(char)(int)((plainTextChar[i]+keyChar[i]-
130)%26+65);
}
System.out.println("Cipher Text="+String.valueOf(cipherTextChar));
char[] recoveredPlainTextChar = new char[cipherTextChar.length];
for(i=0;i<recoveredPlainTextChar.length;i++)
{
recoveredPlainTextChar[i] = (char)(int)((cipherTextChar[i]-
keyChar[i]+26)%26+65);
}
System.out.println("Recovered Plain
Text="+String.valueOf(recoveredPlainTextChar).toLowerCase());
}
}

31
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB

OUTPUT

32
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB

DATA ENCRYPTION STANDARD

SOURCE CODE
import javax.swing.*;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Random ;
class DES {
byte[] skey = new byte[1000];
String skeyString;
static byte[] raw;
String inputMessage,encryptedData,decryptedMessage;

public DES() {
try {
generateSymmetricKey();

inputMessage=JOptionPane.showInputDialog(null,"Enter message to
encrypt");
byte[] ibyte = inputMessage.getBytes();
byte[] ebyte=encrypt(raw, ibyte);

33
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB
String encryptedData = new String(ebyte);
System.out.println("Encrypted message "+encryptedData);
JOptionPane.showMessageDialog(null,"Encrypted Data
"+"\n"+encryptedData);

byte[] dbyte= decrypt(raw,ebyte);


String decryptedMessage = new String(dbyte);
System.out.println("Decrypted message "+decryptedMessage);

JOptionPane.showMessageDialog(null,"Decrypted Data
"+"\n"+decryptedMessage);
}
catch(Exception e) {
System.out.println(e);
}

}
void generateSymmetricKey() {
try {
Random r = new Random();
int num = r.nextInt(10000);
String knum = String.valueOf(num);
byte[] knumb = knum.getBytes();
skey=getRawKey(knumb);
skeyString = new String(skey);

34
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB
System.out.println("DES Symmetric key = "+skeyString);
}
catch(Exception e) {
System.out.println(e);
}
}
private static byte[] getRawKey(byte[] seed) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("DES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(seed);
kgen.init(56, sr);
SecretKey skey = kgen.generateKey();
raw = skey.getEncoded();
return raw;
}
private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception
{
SecretKeySpec skeySpec = new SecretKeySpec(raw, "DES");
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
}

35
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB
private static byte[] decrypt(byte[] raw, byte[] encrypted) throws
Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "DES");
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
public static void main(String args[]) {
DES des = new DES();
}
}

OUTPUT

36
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB

RSA ALGORITHM

SOURCE CODE
import java.io.DataInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Random;

public class RSA


{
private BigInteger p;
private BigInteger q;
private BigInteger N;
private BigInteger phi;
private BigInteger e;
private BigInteger d;
private int bitlength = 1024;
private Random r;
public RSA()
{
r = new Random();
p = BigInteger.probablePrime(bitlength, r);
q = BigInteger.probablePrime(bitlength, r);
N = p.multiply(q);
37
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB
phi =
p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
e = BigInteger.probablePrime(bitlength / 2, r);
while (phi.gcd(e).compareTo(BigInteger.ONE) > 0 &&
e.compareTo(phi) < 0)
{
e.add(BigInteger.ONE);
}
d = e.modInverse(phi);
}
public RSA(BigInteger e, BigInteger d, BigInteger N)
{
this.e = e;
this.d = d;
this.N = N;
}
@SuppressWarnings("deprecation")
public static void main(String[] args) throws IOException
{
RSA rsa = new RSA();
DataInputStream in = new DataInputStream(System.in);
String teststring;
System.out.println("Enter the plain text:");
teststring = in.readLine();
System.out.println("Encrypting String: " + teststring);

38
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB
System.out.println("String in Bytes: "+
bytesToString(teststring.getBytes()));
byte[] encrypted = rsa.encrypt(teststring.getBytes());
byte[] decrypted = rsa.decrypt(encrypted);
System.out.println("Decrypting Bytes: " + bytesToString(decrypted));
System.out.println("Decrypted String: " + new String(decrypted));
}
private static String bytesToString(byte[] encrypted)
{
String test = "";
for (byte b : encrypted)
{
test += Byte.toString(b);
}
return test;
}
public byte[] encrypt(byte[] message)
{
return (new BigInteger(message)).modPow(e, N).toByteArray();
}
public byte[] decrypt(byte[] message)
{
return (new BigInteger(message)).modPow(d, N).toByteArray();
}
}

39
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB

OUTPUT

40
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB

Diffie Hellman

SOURCE CODE
import java.util.*;

class Diffie_Hellman
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter modulo(p)");
int p=sc.nextInt();
System.out.println("Enter primitive root of "+p);
int g=sc.nextInt();
System.out.println("Choose 1st secret no(kuppusamy)");
int a=sc.nextInt();
System.out.println("Choose 2nd secret no(jana)");
int b=sc.nextInt();
int A = (int)Math.pow(g,a)%p;
int B = (int)Math.pow(g,b)%p;
int S_A = (int)Math.pow(B,a)%p;
int S_B =(int)Math.pow(A,b)%p;
if(S_A==S_B)
{
41
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB
System.out.println("ALice and Bob can communicate with each
other!!!");
System.out.println("They share a secret no = "+S_A);
}
else
{
System.out.println("kuppusamy and jana cannot communicate with
each other!!!");
}
}
}

OUTPUT

42
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB

MD5

SOURCE CODE
import java.io.*;
import java.net.*;
import java.util.*;
import java.math.*;
public class MD5
{
private static final int INIT_A = 0x67452301;
private static final int INIT_B = (int) 0xEFCDAB89L;
private static final int INIT_C = (int) 0x98BADCFEL;
private static final int INIT_D = 0x10325476;
private static final int[] SHIFT_AMTS = { 7, 12, 17, 22, 5, 9, 14, 20,
4, 11, 16, 23, 6, 10, 15, 21 };
private static final int[] TABLE_T = new int[64];
static
{
for (int i = 0; i < 64; i++)
TABLE_T[i] = (int) (long) ((1L << 32) * Math.abs(Math.sin(i + 1)));
}
public static byte[] computeMD5(byte[] message)
{
int messageLenBytes = message.length;

43
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB
int numBlocks = ((messageLenBytes + 8) >>> 6) + 1;
int totalLen = numBlocks << 6;
byte[] paddingBytes = new byte[totalLen - messageLenBytes];
paddingBytes[0] = (byte) 0x80;
long messageLenBits = (long) messageLenBytes << 3;
for (int i = 0; i < 8; i++)
{
paddingBytes[paddingBytes.length - 8 + i] = (byte) messageLenBits;
messageLenBits >>>= 8;
}
int a = INIT_A;
int b = INIT_B;
int c = INIT_C;
int d = INIT_D;
int[] buffer = new int[16];
for (int i = 0; i < numBlocks; i++)
{
int index = i << 6;
for (int j = 0; j < 64; j++, index++)
buffer[j >>> 2] = ((int) ((index < messageLenBytes) ?
message[index]: paddingBytes[index - messageLenBytes]) << 24) |
(buffer[j >>> 2] >>> 8);
int originalA = a;
int originalB = b;
int originalC = c;

44
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB
int originalD = d;
for (int j = 0; j < 64; j++)
{
int div16 = j >>> 4;
int f = 0;
int bufferIndex = j;
switch (div16)
{
case 0:
f = (b & c) | (~b & d);
break;
case 1:
f = (b & d) | (c & ~d);
bufferIndex = (bufferIndex * 5 + 1) & 0x0F;
break;
case 2:
f = b ^ c ^ d;
bufferIndex = (bufferIndex * 3 + 5) & 0x0F;
break;
case 3:
f = c ^ (b | ~d);
bufferIndex = (bufferIndex * 7) & 0x0F;
break;
}

45
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB
int temp = b + Integer.rotateLeft(a + f + buffer[bufferIndex] +
TABLE_T[j],SHIFT_AMTS[(div16 << 2) | (j & 3)]);
a = d;
d = c;
c = b;
b = temp;
}
a += originalA;
b += originalB;
c += originalC;
d += originalD;
}
byte[] md5 = new byte[16];
int count = 0;
for (int i = 0; i < 4; i++)
{
int n = (i == 0) ? a : ((i == 1) ? b : ((i == 2) ? c : d));
for (int j = 0; j < 4; j++)
{
md5[count++] = (byte) n;
n >>>= 8;
}
}
return md5;
}

46
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB
public static String toHexString(byte[] b)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < b.length; i++)
{
sb.append(String.format("%02X", b[i] & 0xFF));
}
return sb.toString();
}
public static void main(String[] args)
{
String[] testStrings = { "", "Sanfoundry", "Message Digest",
"abcdefghijklmnopqrstuvwxyz" };
for (String s : testStrings)
System.out.println("0x" + toHexString(computeMD5(s.getBytes())) +
" <== \"" + s + "\"");
return;
}
}

47
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB

OUTPUT

48
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB
Calculate the message digest of a text using the SHA-1 algorithm

Source code
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class GFG


{
public static String encryptThisString(String input)
{
try
{
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] messageDigest = md.digest(input.getBytes());
BigInteger no = new BigInteger(1, messageDigest);
String hashtext = no.toString(16);
while (hashtext.length() < 32)
{
hashtext = "0" + hashtext;
}
return hashtext;
}
catch (NoSuchAlgorithmException e)
{
49
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB
throw new RuntimeException(e);
}
}
public static void main(String args[]) throws
NoSuchAlgorithmException
{
System.out.println("HashCode Generated by SHA-1 for: ");
String s1 = "KUPPUSAMY";
System.out.println("\n" + s1 + " : " + encryptThisString(s1));
String s2 = "hello world";
System.out.println("\n" + s2 + " : " + encryptThisString(s2));
}
}

50
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB

OUTPUT

51
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB

Implementation the signature scheme Digital Signature Standard

Source code
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.Signature;
import java.util.Scanner;

public class DigitalSignature


{
public static void main(String args[]) throws Exception
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter some text");
String msg = sc.nextLine();
KeyPairGenerator keyPairGen =
KeyPairGenerator.getInstance("DSA");
keyPairGen.initialize(2048);
KeyPair pair = keyPairGen.generateKeyPair();
PrivateKey privKey = pair.getPrivate();
Signature sign = Signature.getInstance("SHA256withDSA");
sign.initSign(privKey);
byte[] bytes = "msg".getBytes();

52
KUPPUSAMY.S
M.TECH(NIS)(1ST YEAR)
20394012 CRYPTOGRAPHY LAB
sign.update(bytes);
byte[] signature = sign.sign();
System.out.println("Digital signature for given text: "+new
String(signature, "UTF8"));
}
}

Output

53

You might also like