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

T.Y B.Sc C.

S
SEM V - Information & Network Security
E-Journal
Roll No. 416/B

Name Gaurav Lalit Pandey


CERTIFICATE

This is here to certify that Mr./Ms. Gaurav Lalit Pandey,


Seat Number 416/B of T.Y B.Sc SEM V Computer Science, has
satisfactorily completed the required number of experiments
prescribed by the UNIVERSITY OF MUMBAI during the
academic year 2021 - 2022.

Date:
Place: Mumbai

Teacher In-Charge Head of Department

External Examiner
INDEX

Sr. No. Practical Name Date

1.1 Write a program to execute Caesar’s Cipher. 12/7/2021

1.2 Write a program to execute Mono alphabetic Cipher. 19/7/2021

2 Write a program to execute One Time Pad Cipher 26/7/2021

3.1 Write a program to execute Columnar Cipher. 2/8/2021

3.2 Write a program to execute Railfence Cipher. 16/8/2021

Compute a program to calculate public key and private key


4 23/8/2021
using RSA algorithm.

Compute a program to calculate shared secret key using Diffie


5 6/9/2021
Hellman algorithm.

6 Write a program to execute MD5 algorithm. 13/9/2021

7 Write a program to execute SHA -1 algorithm. 20/9/2021

8 Write a program to implement Socket Programming in java, 27/9/2021


Practical No. 1

Aim: Write a program to implement the following Substitution Cipher Techniques:


-1.1 Caesar Cipher
-1.2 Monoalphabetic Cipher

1.1. Caesar Cipher:


Theory:
-Created by Julius Caesar.
- The Caesar cipher involves replacing each letter of
the alphabet with the letter standing 3 places further
down the alphabet.

Disadvantages of Caesar Cipher:


-Simple structure usage.
-Can only provide minimum security to the
information.
-Frequency of the letter pattern provides a big clue
in deciphering the entire message.

Code:
import java.util.Scanner;

public class ceasars {


public static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
public static String Encrypt(String plainText,int Key)
{
plainText = plainText.toLowerCase();
String cipherText = "";
for (int i = 0; i < plainText.length(); i++)
{
int charPositionPT = ALPHABET.indexOf(plainText.charAt(i));
int finalPosition = charPositionPT+Key;
if(finalPosition > 25)
{
finalPosition = finalPosition - 26;
}
char replaceVal = ALPHABET.charAt(finalPosition);
cipherText += replaceVal;
}
return cipherText;
}
public static String Decrypt(String cipherText,int Key)
{
cipherText = cipherText.toLowerCase();
String plainText = "";
for (int i = 0; i < cipherText.length(); i++)
{
int charPositionCT = ALPHABET.indexOf(cipherText.charAt(i));
int finalPosition = charPositionCT-Key;
if(finalPosition < 0)
{
finalPosition = finalPosition + 26;
}
char replaceVal = ALPHABET.charAt(finalPosition);
plainText += replaceVal;
}
return plainText;
}

public static void main(String[] args) {

//To read input from the keyboard


Scanner sc = new Scanner(System.in);
System.out.println("Enter the String for Encryption: ");
String message = new String();
message = sc.next();
System.out.println("Encrypted Text:");
System.out.println(Encrypt(message, 3));
System.out.println("Decrypted Text:");
System.out.println(Decrypt((Encrypt(message, 3)), 3));
sc.close();
}

Output:
Conclusion: Thus we have studied the implementation of Caesar’s Cipher.

1.2. Monoaplhabetic Cipher:


Theory:
-a.k.a Simple Substitution cipher.
-i.e Substitution is fixed for each letter of the
alphabet.
-So if “A” is replaced by “R”, then everytime in
that plaintext “A will be replaced by “R”.

Code :
import java.util.Scanner;

public class Monoalphabetic {

public static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";


public static String Encrypt(String plainText,int Key)
{
plainText = plainText.toLowerCase();
String cipherText = "";
for (int i = 0; i < plainText.length(); i++)
{
int charPositionPT = ALPHABET.indexOf(plainText.charAt(i));
int finalPosition = charPositionPT+Key;
if(finalPosition > 25)
{
finalPosition = finalPosition - 26;
}
char replaceVal = ALPHABET.charAt(finalPosition);
cipherText += replaceVal;
}
return cipherText;
}
public static String Decrypt(String cipherText,int Key)
{
cipherText = cipherText.toLowerCase();
String plainText = "";
for (int i = 0; i < cipherText.length(); i++)
{
int charPositionCT = ALPHABET.indexOf(cipherText.charAt(i));
int finalPosition = charPositionCT-Key;
if(finalPosition < 0)
{
finalPosition = finalPosition + 26;
}
char replaceVal = ALPHABET.charAt(finalPosition);
plainText += replaceVal;
}
return plainText;
}
public static void main(String[] args) {
//To read input from the keyboard
Scanner sc = new Scanner(System.in);
System.out.println("Enter the String for Encryption: ");
String message = new String();
message = sc.next();

System.out.println("Enter the key for Encryption: ");


int key = sc.nextInt();
System.out.println("Encrypted Text:");
System.out.println(Encrypt(message, key));
System.out.println("Decrypted Text:");
System.out.println(Decrypt((Encrypt(message, key)), key));
sc.close();
}

Output:

Conclusion: Thus we have studied the implementation of Monoalphabetic Cipher.

Practical No. 2
Aim: Write a program to execute One Time Pad Cipher.
Theory :
-Also called as Vernam Cipher or the Perfect Cipher.
-Here plaintext is combined with a random key.
-The Key must be atleast as long as the plaintext.
-Each key is used only once and sender receiver must destroy the key after use.
-There should be only two copies of the keys,1 with sender other
with receiver.
Code :
import java.util.Scanner;

public class Vernam {


public static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
public static String Encrypt(String plainText,String Key)
{
plainText = plainText.toLowerCase();
String cipherText = "";
for (int i = 0; i < plainText.length(); i++) //i = 2
{
int charPositionPT = ALPHABET.indexOf(plainText.charAt(i)); //h = 7
int charPositionKey = ALPHABET.indexOf(Key.charAt(i)); //n = 13
int finalPosition = charPositionPT+charPositionKey;//finalpos = 20
if(finalPosition > 25)
{
finalPosition = finalPosition - 26; //finalpos = 33 - 26 = 7
}
char replaceVal = ALPHABET.charAt(finalPosition); // u
cipherText += replaceVal; //hu
}
return cipherText;
}
public static String Decrypt(String cipherText,String Key)
{
cipherText = cipherText.toLowerCase();
String plainText = "";
for (int i = 0; i < cipherText.length(); i++)
{
int charPositionCT = ALPHABET.indexOf(cipherText.charAt(i));
int charPositionKey = ALPHABET.indexOf(Key.charAt(i));
int finalPosition = charPositionCT-charPositionKey;
if(finalPosition < 0)
{
finalPosition = finalPosition + 26;
}
char replaceVal = ALPHABET.charAt(finalPosition);
plainText += replaceVal;
}
return plainText;
}

public static void main(String[] args) {

//To read input from the keyboard


Scanner sc = new Scanner(System.in);
System.out.println("Enter the String for Encryption: ");
String message = new String();
message = sc.next();
//Take the Key as input
System.out.println("Enter the key for Encryption: ");
String key = new String();
key = sc.next();

if (message.length() == key.length()) {
System.out.println("Encrypted Text:");
System.out.println(Encrypt(message, key));
System.out.println("Decrypted Text:");
System.out.println(Decrypt((Encrypt(message, key)), key));
}
else
System.out.println("Please enter same length Plaintext and keyword.");
sc.close();
}
}

Output :

Conclusion: Thus we have studied the implementation of Vernam Cipher.

Practical No. 3
Aim: Write programs to implement the following Transposition Cipher
Techniques:
- 3.1.Simple Columnar Technique
- 3.2.Rail Fence Cipher

3.1.Columnar Cipher:
Theory:
-The message is written out in rows of a fixed length, and then read out again
column by column, and the columns are chosen in some scrambled order.
-Width of the rows and the permutation of the columns are usually defined
by a keyword.
-For example, the word HACK is of length 4 (so the rows are of length 4),
and the permutation is defined by the alphabetical order of the letters in the
keyword. In this case, the order would be “3 1 2 4”.
-Any spare spaces are filled with nulls or left blank or placed by Filler alphabets.
Code :
import java.util.Scanner;

public class Columnar {


public static void Encrypt(String plainText, String key)
{
//make string arrays of key and plaintext
String pt[]=plainText.split(""); //blue = {"b","l","u","e"}
String ky[]=key.split(""); //ab = {"a","b"}
//get the no of columns and rows to build matrix
int columns = key.length();
int rows;
if(plainText.length() % columns == 0)
{
rows = (plainText.length())/columns + 1;
}
else
{
rows = (plainText.length()/columns) + 2; //
}

String[][] mat = new String[rows][columns];


String var="";
int c = 0;

//enter key in first row of matrix


for(int i = 0; i < columns; i++)
{
mat[0][i] = ky[i];
}

//fill up the matrix with plaintext


for(int i = 1; i < rows; i++)
{
for(int j = 0; j< columns; j++)
{
if(c != plainText.length()) // C = 2 , plaintext = 18
{
var = pt[c]; // N
mat[i][j]=var; //
//System.out.print(mat[i][j]+"\t");
c++;
}
else
break;
}
//System.out.println();
}

//pad the empty spaces with either numeric values or characters


for(int i = 0; i < rows; i++)
{
for(int j = 0; j< columns; j++)
{
if(mat[i][j] == null)
{
mat[i][j]="X";
}
}
}

//display the matrix


for(int i = 0; i < rows; i++)
{
for(int j = 0; j< columns; j++)
{
System.out.print(mat[i][j]+"\t");
}
System.out.println();
}

//COLUMNAR LOGIC

//display the encrypted string


String output="";
for(int i = 0; i < columns; i++)
{
for(int j = 1; j< rows ; j++)
{
output=output+mat[j][i];

}
}
System.out.println("Encrypted String: "+output);
}

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);


System.out.println("Enter the String for Encryption: ");
String str = new String();
str = sc.next();
System.out.println("Enter the key for Encryption: ");
String key = new String();
key = sc.next();
Encrypt(str,key);
}

Output :

Conclusion : Thus we have studied the implementation of Columnar Cipher.


3.2.Railfence Cipher:
Theory:
-The rail fence cipher (also called a zigzag cipher) is a form of
transposition cipher.
-It derives its name from the way in which it is encoded.In the rail
fence cipher, the plain-text is written downwards and diagonally on
successive rails of an imaginary fence.
-When we reach the bottom rail, we traverse upwards moving
diagonally, after reaching the top rail, the direction is changed
again. Thus the alphabets of the message are written in a zig-zag
manner.

Code :
import java.util.Arrays;
import java.util.Scanner;

public class Railfence {


public static void Encrypt(String str, int n)
{
//if depth = 1
if (n == 1)
{
System.out.print(str);
return ;
}
char[] str1 = str.toCharArray();//"youneedtostudy" = {"y","o","u","n"....}
int len = str.length(); //len = columns
String[] arr = new String[n]; //n = key = rows
Arrays.fill(arr, "");
int row = 0; //pointer to the row
boolean down = true;
//LEN = NO OF COLUMNS OR PLAINTEXT SIZE
for (int i = 0; i < len; i++) //i becomes pointer of columns
{
arr[row] = arr[row] + (str1[i]); //str1 = {I,L,I,V,E,I,N,M,U,M..}
if (row == n - 1) //2 == 2
{
down = false;
}
else if (row == 0) //2 == 0
{
down = true;
}
if (down)
{
row++;
}
else
{
row--;
}
}

for (int i = 0; i < n; i++)


{
System.out.print(arr[i]);
}
}

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);


System.out.println("Enter the String for Encryption: ");
String str = new String();
str = sc.next(); //plaintext from user
int n = 3; //key / rows
System.out.println("Encrypted String:");
Encrypt(str, n);
}

Output :

Conclusion : Thus we have studied the implementation of Railfence Cipher.

Practical No. 4
Aim: Write a program to implement RSA algorithm to perform encryption /
decryption of a given string.

Theory:
-RSA algorithm is a public key encryption technique and is considered as the
most secure way of encryption.
-It was invented by Rivest, Shamir and Adleman in year 1978 and hence name
RSA algorithm.
-The entire RSA is all about creating public key, private key for encryption and
decryption.
-Lets see the encryption algorithm in detail.
RSA Logic:

To encrypt Sender will use:


C = Pe mod N (C is Cipher Text)
To Decrypt Reciever will use:
P = Cd mod N (P is Plain Text)
where e = Public key, d = Private key and N is a large number.
All these three numbers are calculated using RSA.

Code :
import java.util.Scanner;

public class rsa {

public static int pvtkey; //y

public static void ComputeRSA(int p,int q)


{
//Step 1: Calculate RSA Modulus
int N;
N = p * q;

//Step 2: Calculate Derived Number


int m;
m = (p-1)*(q-1);

//Step 3: Choose a public key that follows the two conditions of


// 1< e < m
// e is a prime number
int e; //public key
Scanner sc = new Scanner(System.in);
System.out.println("Enter value for public key");
e = sc.nextInt();
boolean isPrime = checkForPrime(e);
//checking if e is greater than 1 and lesser than derived number m
if (e > 1 && e < m) {
if (isPrime) { //isPrime for e

//Step 4 : Constructing the table


int[] a = new int[25];
int[] b = new int[25];
int[] d = new int[25];
int[] k = new int[25];

//Giving the default values


//1st row
a[0] = 1; b[0] = 0; d[0] = m; k[0] = 0;
//2nd row
a[1] = 0; b[1] = 1; d[1] = e;
k[1] = d[0] / d[1];

//loop that checks if d = 1 and stops at that point


System.out.println("a \t b \t d \t k");
int i = 2;
while (d[i] != 1) {
a[i] = a[i - 2] - (a[i - 1] * k[i - 1]);
b[i] = b[i - 2] - (b[i - 1] * k[i - 1]);
d[i] = d[i - 2] - (d[i - 1] * k[i - 1]);
k[i] = d[i - 1] / d[i];
System.out.println(a[i] + "\t " + b[i] + "\t " + d[i] + "\t "
+ k[i]);

if (d[i] == 1)
{
pvtkey = b[i];
break;
}
else
{
i++;
}

}
//Step 5: Applying conditions on your private key
if (pvtkey > m) {
pvtkey = pvtkey % m;
}
if (pvtkey < 0) {
pvtkey = pvtkey + m;
}

//Printing the public and private key


System.out.println();

System.out.println("*************************************************");
System.out.println("Public Key: " + e);
System.out.println("Private Key: " + pvtkey);

System.out.println("*************************************************");
}
else
System.out.println("The public key you chose is not a prime
number.");
}
else
System.out.println("The public key you chose is bigger than derived number
" +m);
}

public static boolean checkForPrime(int inputNumber)


{
boolean isItPrime = true;

if(inputNumber <= 1)
{
isItPrime = false;
return isItPrime;
}
else
{
for (int i = 2; i<= inputNumber/2; i++)
{
if ((inputNumber % i) == 0)
{
isItPrime = false;
break;
}
}

return isItPrime;
}
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.println("Enter value for p(prime no. 1)- ");
int p;
p = sc.nextInt();
boolean isPrime = checkForPrime(p);
if(isPrime) //isPrime = true for p
{
System.out.println("Enter value for q(prime no. 2)- ");
int q;
q = sc.nextInt();
isPrime = checkForPrime(q);
if(isPrime) //isPrime = true for q
{
ComputeRSA(p,q);
}
else
System.out.println("q is not a prime number.");
}
else
System.out.println("p is not a prime number.");
}

Output :

Conclusion : Thus we have studied the implementation of RSA.


Practical No. 5
Aim: Write a program to implement the Diffie-Hellman Key Agreement
algorithm to generate symmetric keys.

Theory:
-The Diffie–Hellman key exchange method allows two parties that have no prior
knowledge of each other to jointly establish a shared secret key over an insecure
channel.
-This key can then be used to encrypt and decrypt subsequent communications
using a symmetric key cipher.
-The whole point is to share a secret symmetric key between alice and bob which
they can use for further communication.

Code :
import java.util.Scanner;

public class DFH {

public static void ComputeDF(double q, double p)


{
//Step 2: Compute CipherKey for Alice and Bob
Scanner sc = new Scanner(System.in);
System.out.println("Enter private key for Alice:");
double pvtAlice = sc.nextInt();
System.out.println("Enter private key for Bob:");
double pvtBob = sc.nextInt();
double cipherKeyAlice, cipherKeyBob;
cipherKeyAlice = Math.pow(p, pvtAlice) % q;
cipherKeyBob = Math.pow(p, pvtBob)% q;
//System.out.println("Cipher Key of Alice :"+cipherKeyAlice);
//System.out.println("Cipher Key of Bob :"+cipherKeyBob);
//Step 3: Compute Shared Secret Key
double SecretKeyAlice = Math.pow(cipherKeyBob, pvtAlice) %q;
double SecretKeyBob = Math.pow(cipherKeyAlice, pvtBob) %q;

if (SecretKeyAlice == SecretKeyBob)
{
System.out.println("Shared Secret Key = " + (int)SecretKeyAlice);
}
else
System.out.println("Your values don't match. Please try again.");
sc.close();
}

public static boolean checkForPrime(double inputNumber)


{
boolean isItPrime = true;

if(inputNumber <= 1)
{
isItPrime = false;
return isItPrime;
}
else
{
for (int i = 2; i<= inputNumber/2; i++)
{
if ((inputNumber % i) == 0)
{
isItPrime = false;
break;
}
}

return isItPrime;
}
}

public static void main(String[] args) {


//Step 1 : take q and p as input
Scanner sc = new Scanner(System.in);
System.out.println("Enter value for q(prime no.)- ");
double q;
q = sc.nextInt();
boolean IsPrime = checkForPrime(q);
if (IsPrime)
{
System.out.println("Enter value for p(primitive root of q)- ");
double p;
p = sc.nextInt();
ComputeDF(q, p);
}
else
System.out.println("The value you entered for q is not prime number. Please
try again.");

Output :
Conclusion : Thus we have studied the implementation of Diffie-Hellman Key
Agreement.

Practical No. 6
Aim: Write a program to implement the MD5 algorithm compute the message
digest.

Theory:
-Message Digest is used to ensure the integrity of a message transmitted over an
insecure channel (where the content of the message can be changed).
-The message is passed through a
-Cryptographic hash function. This function creates a compressed image of the
message called Digest.
-Produces 128 bit message digest.
-Lets assume, Alice sent a message and digest pair to Bob. To check the integrity
of the message Bob runs the cryptographic hash function on the received
message and gets a new digest.
-Now, Bob will compare the new digest and the digest sent by Alice. If, both are
same then Bob is sure that the original message is not changed.

Code :
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5 {

public static String getMd5(String input) throws NoSuchAlgorithmException


{

// Static getInstance method is called with hashing MD5


MessageDigest md = MessageDigest.getInstance("SHA-1");

// digest() method is called to calculate message digest


// of an input digest() return array of byte
byte[] messageDigest = md.digest(input.getBytes());

// Convert byte array into signum representation - convert byte array to a


positive magnitute
BigInteger no = new BigInteger(1, messageDigest);

// Convert message digest into hex value


String hashtext = no.toString(16);

return hashtext;

// Driver code
public static void main(String args[]) throws NoSuchAlgorithmException
{
String s = "Thakur";
System.out.println("Your HashCode Generated by MD5 is: " + getMd5(s));
}

Output :

Conclusion : Thus we have studied the implementation of MD5 algorithm.

Practical No. 7
Aim: Write a program to calculate HMAC-SHA1 Signature.

Theory:
-In cryptography, SHA-1 (Secure Hash Algorithm 1) is a cryptographic hash
function which takes an input and produces a 160-bit (20-byte) hash value known
as a message digest
-This was designed by the National Security Agency (NSA) to be part of the
Digital Signature Algorithm. Cryptographic weaknesses were discovered in
SHA-1, and the standard was no longer approved for most cryptographic uses
after 2010.
Code :
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class SHA {

public static String getSHA(String input) throws NoSuchAlgorithmException


{

// Static getInstance method is called with hashing MD5


MessageDigest md = MessageDigest.getInstance("SHA-1");

// digest() method is called to calculate message digest


// of an input digest() return array of byte
byte[] messageDigest = md.digest(input.getBytes());

// Convert byte array into signum representation - convert byte array to a positive
magnitute
BigInteger no = new BigInteger(1, messageDigest);

// Convert message digest into hex value


String hashtext = no.toString(16);

return hashtext;

// Driver code
public static void main(String args[]) throws NoSuchAlgorithmException
{
String s = "Thakur";
System.out.println("Your HashCode Generated by SHA-1 is: " + getSHA(s));
}

Output :

Conclusion : Thus we have studied the implementation of SHA-1 algorithm.

Practical No. 8
Aim: Write a program to implement Socket Programming in java.
Theory:
-A socket is one endpoint of a two-way communication link between two
programs running on the network.
-A socket is bound to a port number so that the TCP layer can identify the
application that data is destined to be sent to.
-An endpoint is a combination of an IP address and a port number. Every TCP
connection can be uniquely identified by its two endpoints. That way you can
have multiple connections between your host and the server.
-The java.net package in the Java platform provides a class, Socket, that
implements one side of a two-way connection between your Java program and
another program on the network.

Code :
Server.java
package server;

import java.io.*;
import java.net.*;

public class Server {

public static void main(String[] args) {

try
{
//ServerSocket class provides a mechanism for the server program to listen
for clients
ServerSocket ss=new ServerSocket(6666);
//establishes connection
Socket s=ss.accept();
//Data Input stream creates a stream to read the incoming data
DataInputStream dis=new DataInputStream(s.getInputStream());
//readUTF reads the incoming streaming data in string format
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}
catch(Exception e)
{
System.out.println(e);}
}

}
Client.java
package client;
import java.net.*;
import java.io.*;

public class Client {

public static void main(String[] args) {

try{
//Creates a connection to mentioned port and
//first arg deals with ip address of the server machine, in our case it is
the same machine so localhost
Socket s = new Socket("localhost",6666);
//Creates a stream to send data
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
//Writes data in String format
dout.writeUTF("Hello Server!");
//flush() method clears the stream
dout.flush();
dout.close();
s.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Output :

Conclusion : Thus we have studied the implementation of Socket Algorithm.

You might also like