0% found this document useful (0 votes)
4 views

cys_lab_manual

The document is a lab manual for the Cryptography and Cyber Security course at SSM Institute of Engineering and Technology, detailing the vision, mission, program educational objectives, outcomes, and specific outcomes for students. It includes laboratory rules, practical exercises, and a syllabus with various encryption techniques and algorithms to be implemented. Additionally, it outlines the equipment needed for the course and provides a mapping of course outcomes to program outcomes and specific outcomes.

Uploaded by

ssmcsesudhakar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

cys_lab_manual

The document is a lab manual for the Cryptography and Cyber Security course at SSM Institute of Engineering and Technology, detailing the vision, mission, program educational objectives, outcomes, and specific outcomes for students. It includes laboratory rules, practical exercises, and a syllabus with various encryption techniques and algorithms to be implemented. Additionally, it outlines the equipment needed for the course and provides a mapping of course outcomes to program outcomes and specific outcomes.

Uploaded by

ssmcsesudhakar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

SSM INSTITUTE OF ENGINEERING AND TECHNOLOGY

(AN AUTONOMOUS INSTITUTION)


(Approved by AICTE, New Delhi /Affiliated to Anna University /Accredited by NAAC)
Dindigul – Palani Highway, Dindigul – 624 002.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


(CYBER SECURITY)

LAB MANUAL

COURSE CODE CB3411

COURSENAME CRYPTOGRAPHY AND CYBER SECURITY

REGULATION 2021 R

YEAR/SEM II / IV

Prepared by Approved by
Dr. S. SUDHAKAR, AsP/CSE Dr. K. RAJESH Professor
HOD/CSE (CYBER SECURITY)
SSM INSTITUTE OF ENGINEERING AND TECHNOLOGY
(AN AUTONOMOUS INSTITUTION)
(Approved by AICTE, New Delhi / Affiliated to Anna University/Accredited by NAAC)
Dindigul – Palani Highway, Dindigul – 624 002.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


(CYBER SECURITY)

VISION

To develop skilled cyber security professionals equipped to secure digital landscapes, address emerging
cyber challenges, and contribute to society with strong technical expertise, entrepreneurial skills, and
ethical values.

MISSION

 Foster self-discipline and critical thinking in students through robust teaching and learning.
 Empower students to become proficient cyber security professionals and responsible citizens.
 Strengthen industry partnerships by establishing specialized centres for advanced skill
development and practical exposure.
 Deliver knowledge for secure and innovative solutions, contributing to sustainable and ethical
technology advancement.

PROGRAM EDUCATIONAL OBJECTIVES (PEOs)

PEO1 Graduates can apply their technical competence in computer science to solve real world
problems, with technical and people leadership.

Graduates Conduct cutting edge research and develop solutions on problems of social
PEO2 relevance.

Graduates will Work in a business environment, exhibiting team skills, work ethics,
PEO3 adaptability and lifelong learning.
PROGRAM OUTCOMES (POs)

Graduate Attribute

1 Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering problems.

2 Problem analysis: Identify, formulate, review research literature, and analyse complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.

3 Design/development of solutions: Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with appropriate consideration for the
public health and safety, and the cultural, societal, and environmental considerations.

4 Conduct investigations of complex problems: Use research-based knowledge and research


methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.

5 Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modelling to complex engineering activities with
an understanding of the limitations.

6 The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.

7 Environment and sustainability: Understand the impact of the professional engineering


solutions in societal and environmental contexts, and demonstrate the knowledge of, and need for
sustainable development.

8 Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms
of the engineering practice.

9 Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
10 Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive clear
instructions.

11 Project management and finance: Demonstrate knowledge and understanding of the


engineering and management principles and apply these to one’s own work, as a member and leader
in a team, to manage projects and in multidisciplinary environments.

12 Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.

PROGRAM SPECIFIC OUTCOMES (PSOs)

The Students will be able to


 Exhibit design and programming skills to build and automate business solutions using cutting
edge technologies.
 Strong theoretical foundation leading to excellence and excitement towards research, to provide
elegant solutions to complex problems.
 Ability to work effectively with various engineering fields as a team to design, build and develop
system applications.
SSM INSTITUTE OF ENGINEERING AND TECHNOLOGY
(AN AUTONOMOUS INSTITUTION)
(Approved by AICTE, New Delhi / Affiliated to Anna University / Accredited by NAAC)
Dindigul – Palani Highway, Dindigul – 624 002

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


(CYBER SECURITY)

Do’s and Don’ts


Laboratory Rules &Regulation:
 Students are instructed to maintain silence inside the Lab.
 Students have to sign the log-book, while entering and leaving the Lab and also they have
to mention the time in and time out.
 Students have to enter and leave the Lab in their scheduled time otherwise they will be
marked absent.
 Students should come with proper Lab uniform and with shoes.
 The students should properly shut down the Computer Systems before they leave the Lab.
 Students are not allowed to use CD’s & DVD’s, USB DRIVE etc. lf required
prior permission of Laboratory in-charge is needed.
 All students will be responsible for keeping the Lab clean.
 Students should refrain from dislocating, shifting and damaging with any parts of
the computer or any other device in the Lab.
 The students should not load or delete any software from the computer.
 The students should not use computers in the Lab for any personal work.
 Browsing of Internet will not be allowed in the lab beyond the stipulated hour as per time
table.
 The Instructor/Lecturer will be the sole authority to judge the disciplinary behavior
inside the laboratory. For violation of any of the above rules, the department reserves the
right to take appropriate disciplinary action.
 Browsing of non-academic Internet sites will not be allowed in the Lab.
 Before downloading any materials please consult your instructor and save the
downloaded files as per instruction given by the laboratory in- charge.
 Because of security problems, downloading software and music etc. from the
Internet is strictly prohibited. Any such file found in the hard disk will be deleted
without warning.
 Students should arrange the chairs properly while leaving the LAB hours.
 Students should not allow to work inside the LAB other than LAB hours. If required
prior permission of Laboratory in-charge and Department in charge is needed.
SYLLABUS

CB3411 CRYPTOGRAPHY AND CYBER SECURITY LABORATORY LTPC


0 0 3 1.5

COURSE OBJECTIVES:
 Learn different cipher techniques.
 Implement the algorithms DES, AES, RSA and Diffie-Hellman.
 Implement hashing techniques such as SHA-1, MD-5.
 Develop a digital signature scheme.

PRACTICAL EXERCISES:
1. Write a program to implement the following cipher techniques to perform encryption and
decryption
i. Caesar Cipher
ii. Playfair Cipher
iii. Hill Cipher
2. Write a program to implement the following transposition techniques
(i) Rail fence technique –Row major transformation
(ii) Rail fence technique - Column major transformation
3. Write a program to implement DES algorithm
4. Write a program to implement AES algorithm
5. Write a program to implement RSA Encryption algorithm
6. Write a program to implement the Diffie-Hellman Key Exchange mechanism. Consider one of
the parties as Alice and the other party as bob.
7. Write a program to calculate the message digest of a text using the SHA-1 algorithm.
8. Write a program to calculate the message digest of a text using the MD-5 algorithm.
9. Write a program to implement digital signature standard.

TOTAL: 30 PERIODS
COURSE OUTCOMES:
CO1: Develop a code for classical encryption techniques.
CO2: Build a symmetric and asymmetric algorithms.
CO3: Construct a code for various Authentication schemes.
CO4: Apply the principles of digital signature.
LIST OF EQUIPMENT FOR A BATCH OF 30 STUDENTS:
SOFTWARE: C / C++ / Java or equivalent compiler
HARDWARE: Standalone desktops – 30 Nos. (or) Server supporting 30 terminals or more.

CO – PO’S & PSO’S Mapping:

CO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2
CB3411.1 3 3 3 3 3 - - - 3 - - 1 3 3
(CO1)
CB3411.2 3 3 3 3 3 - - - 3 - - 1 3 3
(CO2)
CB3411.3 3 3 3 3 3 - - - 3 - - 1 3 3
(CO3)
CB3411.4 3 3 3 3 3 - - - 3 - - 1 3 3
(CO4)
Avg. 3 3 3 3 3 - - - 3 - - 1 3 3

Note: Enter correlation levels 1, 2 or 3 as defined below:

1: Slight (Low) 2: Moderate (Medium) 3: Substantial (High)

It there is no correlation, put “-”


TABLE OF CONTENTS

S.NO DATE TITLE OF THE EXPERIMENT MARKS SIGN

1 Perform encryption, decryption using the


following substitution techniques.
1(a) Caesar Cipher
1(b) Playfair Cipher
1(c) Hill Cipher
2 Perform encryption and decryption using
following transposition techniques.
2(a) Rail fence
2(b) Row & Column Transformation
3 Data Encryption Standard (DES)
4 Advanced Encryption Standard (AES)
5 RSA Algorithm
6 Diffie-Hellman Key Exchange Algorithm
7 Secure Hash Algorithm (SHA-1)
8 Message Digest Algorithm(MD-5)

9 Digital Signature Standard (DSA)

CONTENT BEYOND THE SYLLABUS


S.NO DATE TITLE OF THE PROGRAM MARKS SIGN

10 Intrusion Detection System (IDS)

11 Blowfish Algorithm Logic


Ex.No. : 1a CAESAR CIPHER
Date :

AIM:
To implement a Caesar cipher substitution technique in Java.

ALGORITHM:
1. Assign the 26 letters in alphabet to the variable named ALPHABET.
2. Convert the plaintext letters into lowercase.
3. To encrypt a plaintext letter, the first set of plaintext letters and slides it to LEFT by the
number of positions of the secret shift.
4. The plaintext letter is then encrypted to the ciphertext letter on the sliding ruler underneath.
5. On receiving the ciphertext, the receiver who also knows the secret shift, positions his
sliding ruler underneath the ciphertext alphabet and slides it to RIGHT by the agreed shift
number, 3 in this case.
6. Then replaces the ciphertext letter by the plaintext letter on the sliding ruler underneath.

PROGRAM:
import java.util.Scanner;
public class ceasercipher
{
public static final String ALPHABET="abcdefghijklmnopqrstuvwxyz";
public static String encrypt(String plainText,int shiftKey)
{
plainText=plainText.toLowerCase();
String cipherText="";
for (int i=0; i<plainText.length();i++)
{
int charPosition=ALPHABET.indexOf(plainText.charAt(i));
int keyVal=(shiftKey+charPosition)%26;
char replaceVal=ALPHABET.charAt(keyVal);
cipherText+=replaceVal;
}
return cipherText;
}
public static String decrypt(String cipherText,int shiftKey)
{
cipherText = cipherText.toLowerCase();
String plainText = "";
for(int i=0;i<cipherText.length();i++)
{
int charPosition= ALPHABET. indexOf(cipherText. charAt(i));
int keyVal=(charPosition-shiftKey)%26;
if (keyVal< 0)
{
keyVal=ALPHABET.length()+keyVal;
}
char replaceVal=ALPHABET.charAt(keyVal);
plainText+=replaceVal;
}
return plainText;
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the Plain text for Encryption: ");
String message=new String();
message=sc.next();
System.out.println("Encrypted message:Cipher Text="+encrypt(message,3));
System.out.println("Decrypted message:Plain Text="+decrypt (encrypt(
message,3),3));
sc.close();
}
}

OUTPUT:
F:\bin>javac ceasercipher.java
F:\bin>java ceasercipher
Enter the Plain text for Encryption:
covid
Encrypted message:Cipher Text=frylg
Decrypted message:Plain Text=covid

RESULT:
Thus the Caesar cipher substitution technique was implemented and executed
successfully.
Ex.No. : 1b PLAYFAIR CIPHER
Date :

AIM:
To implement a Playfair cipher substitution technique in Java.

ALGORITHM:
1. Read the keyword.
2. Then create the key table of 5x5 grid of alphabets.
3. Read the word to encrypt.
4. Ifthe input word should be even and then process it.
5. Then the plaintext message is split into pairs of two letters (digraphs).
6. Ifboth the letters are in the same column, take the letter below each one.
7. Ifboth letters are in the same row, take the letter to the right of each one.
8. 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.

PROGRAM:
import java.util.Scanner;
public class Playfair1
{
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
System.out.print("Enter keyword: ");
String key=in.nextLine();
System.out.print("Enter message to encrypt: ");
String msg=in.nextLine();
PFEncryption pfEncryption=new PFEncryption();
pfEncryption.makeArray(key);
msg=pfEncryption.manageMessage(msg);
pfEncryption.doPlayFair(msg, "Encrypt");
String en=pfEncryption.getEncrypted();
System.out.println("Encrypting. .. \n\nThe encrypted text is: " + en);
System.out.println("=============================");
pfEncryption.doPlayFair(en, "Decrypt");
System.out.print("\nDecrypting... \n\nThe encrypted text is: " +
pfEncryption.getDecrypted());
}
}
class PFEncryption
{
private char [][] alphabets= new char[5][5];
private char[] uniqueChar= new char[26];
private String ch="ABCDEFGHIKLMNOPQRSTUVWXYZ";
private String encrypted="";
private String decrypted="";
void makeArray(String keyword)
{
keyword=keyword.toUpperCase().replace("J","I");
boolean present, terminate=false;
int val=0;
int uniqueLen;
for (int i=0; i<keyword.length(); i++)
{
present=false;
uniqueLen=0;
if (keyword.charAt(i)!= ' ')
{
for (int k=0; k<uniqueChar.length; k++)
{
if (Character.toString(uniqueChar[k])==null)
{
break;
}
uniqueLen++;
}
for (int j=0; j<uniqueChar.length; j++)
{
if (keyword.charAt(i)==uniqueChar[j])
{
present=true;
}
}
if (!present)
{
uniqueChar[val]=keyword.charAt(i);
val++;
}
}
ch=ch.replaceAll(Character.toString(keyword.charAt(i)), "");
}
for (int i=0; i<ch.length(); i++)
{
uniqueChar[val]=ch.charAt(i);
val++;
}
val=0;

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


{
for (int j=0; j<5; j++)
{
alphabets[i][j]=uniqueChar[val];
val++;
System.out.print(alphabets[i][j] + "\t");
}
System.out.println();
}
}
String manageMessage(String msg)
{
int val=0;
int len=msg.length()-2;
String newTxt="";
String intermediate="";
while (len>=0)
{
intermediate=msg.substring(val, val+2);
if (intermediate.charAt(0)==intermediate.charAt(1))
{
newTxt=intermediate.charAt(0) + "x" + intermediate.charAt(1);
msg=msg.replaceFirst(intermediate, newTxt);
len++;
}
len-=2;
val+=2;
}
if (msg.length()%2!=0)
{
msg=msg+'x';
}
return msg.toUpperCase().replaceAll("J","I").replaceAll(" ","");
}
void doPlayFair(String msg, String tag)
{
int val=0;
while (val<msg.length())
{
searchAndEncryptOrDecrypt(msg.substring(val,val+2),tag);
val+=2;
}}
void searchAndEncryptOrDecrypt(String doubblyCh, String tag)
{
char ch1=doubblyCh.charAt(0);
char ch2=doubblyCh.charAt(1);
int row1=0, col1=0, row2=0, col2=0;
for (int i=0; i<5; i++)
{
for (int j=0; j<5; j++)
{
if (alphabets[i][j]==ch1)
{
row1=i;
col1=j;
}
else if (alphabets[i][j]==ch2)
{
row2=i;
col2=j;
} } }
if (tag=="Encrypt")
encrypt(row1, col1, row2, col2);
else if(tag=="Decrypt")
decrypt(row1, col1, row2, col2);
}
void encrypt(int row1, int col1, int row2, int col2)
{
if (row1==row2)
{
col1=col1+1;
col2=col2+1;
if (col1>4)
col1=0;
if (col2>4)
col2=0;
encrypted+=(Character.toString(alphabets[row1][col1])+
Character.toString(alphabets[row1][col2]));
}
else if(col1==col2)
{
row1=row1+1;
row2=row2+1;
if (row1>4)
row1=0;
if (row2>4)
row2=0;
encrypted+=(Character.toString(alphabets[row1][col1])+
Character.toString(alphabets[row2][col1]));
}
else
{ encrypted+=(Character.toString(alphabets[row1][col2])+
Character.toString(alphabets[row2][col1]));
}}
void decrypt(int row1, int col1, int row2, int col2)
{
if (row1==row2)
{
col1=col1-1;
col2=col2-1;
if (col1<0)
col1=4;
if (col2<0)
col2=4;
decrypted+=(Character.toString(alphabets[row1][col1])+
Character.toString(alphabets[row1][col2]));
}
else if(col1==col2)
{
row1=row1-1;
row2=row2-1;
if (row1<0)
row1=4;
if (row2<0)
row2=4;
decrypted+=(Character.toString(alphabets[row1][col1])+
Character.toString(alphabets[row2][col1]));
}
else
{
decrypted+=(Character.toString(alphabets[row1][col2])+
Character.toString(alphabets[row2][col1]));
}}
String getEncrypted( )
{
return encrypted;
}
String getDecrypted( )
{
return decrypted;
}}

OUTPUT:
F:\bin>javac Playfair1.java

F:\bin>java Playfair1
Enter keyword: INFOSEC
Enter message to encrypt: cryptography
I N F O S
E C A B D
G H K L M
P Q R T U
V W X Y Z
Encrypting....

The encrypted text is: AQVTYBKPERLW


=======================================

Decrypting....

The encrypted text is: CRYPTOGRAPHY

RESULT:
Thus the Playfair cipher substitution technique was implemented and executed
successfully.
Ex.No. : 1c HILL CIPHER
Date :

AIM:
To implement a Hill cipher substitution technique in Java.

ALGORITHM:
1. Obtain a plaintext message to encode in standard English with no spaces.
2. Split the plaintext into group of length three. To fill this, add X at the end.
3. Convert each group of letters with length three into plaintext vectors.
4. Replace each letter by the number corresponding to its position in the alphabet i.e.
A=1, B=2, C=3…Z=0.
5. Create the keyword in a 3*3 matrix.
6. Multiply the two matrices to obtain the cipher text of length three.
7. For decryption, convert each entry in the ciphertext vector into its plaintext vector by
multiplying the cipher text vector and inverse of a matrix.
8. Thus plain text is obtained fromcorresponding plaintext vector by corresponding
position in the alphabet.

PROGRAM:
import java.util.Scanner;
import javax.swing.JOptionPane;
public class hillcipher
{
//the 3x3 key matrix for 3 characters at once
public static int[][] keymat = new int[][]
{
{ 1, 2, 1 },
{ 2, 3, 2 },
{ 2, 2, 1 },
};
public static int[][] invkeymat = new int[][]
{
{ -1, 0, 1 },
{ 2, -1, 0 },
{ -2, 2, -1},
};
public static String key = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

public static void main(String[] args)


{
String text,outtext ="",outtext1="";
int ch, n;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the Plain text for Encryption: ");
//String text=new String();
text=sc.next();

text = text.toUpperCase();
text = text.replaceAll("\\s",""); //removing spaces
n = text.length() % 3;
if(n!=0)
{
for(int i = 1; i<= (3-n);i++)
{
text+= 'X';
}
}
System.out.println("Padded Text:" + text);
char[] ptextchars = text.toCharArray();
for(int i=0;i< text.length(); i+=3)
{
outtext += encrypt(ptextchars[i],ptextchars[i+1],ptextchars[i+2]);
}
System.out.println("Encypted Message: " + outtext);

char[] ptextchars1 = outtext.toCharArray();


for(int i=0;i< outtext.length(); i+=3)
{
outtext1 += decrypt(ptextchars1[i],ptextchars1[i+1],ptextchars1[i+2]);
}
System.out.println("Decrypted Message: " + outtext1);
}

private static String encrypt(char a, char b, char c)


{
String ret = "";
int x,y, z;
int posa = (int)a - 65;
int posb = (int)b - 65;
int posc = (int)c - 65;
x = posa * keymat[0][0] + posb * keymat[1][0] + posc * keymat[2][0];
y = posa * keymat[0][1] + posb * keymat[1][1] + posc * keymat[2][1];
z = posa * keymat[0][2] + posb * keymat[1][2] + posc * keymat[2][2];
a = key.charAt(x%26);
b = key.charAt(y%26);
c = key.charAt(z%26);
ret = "" + a + b + c;
return ret;
}

private static String decrypt(char a, char b, char c)


{
String ret = "";
int x,y,z;
int posa = (int)a - 65;
int posb = (int)b - 65;
int posc = (int)c - 65;
x = posa * invkeymat[0][0]+ posb * invkeymat[1][0] + posc * invkeymat[2][0];y
= posa * invkeymat[0][1]+ posb * invkeymat[1][1] + posc * invkeymat[2][1];
z = posa * invkeymat[0][2]+ posb * invkeymat[1][2] + posc * invkeymat[2][2];
a = key.charAt((x%26<0)?(26+x%26):(x%26));
b = key.charAt((y%26<0)?(26+y%26):(y%26));
c = key.charAt((z%26<0)?(26+z%26):(z%26));
ret = "" + a + b + c;
return ret;
}
}

OUTPUT:
F:\bin>javac hillcipher.java

F:\bin>java hillcipher
Enter the Plain text for Encryption:
mothertheresa
Padded Text:MO THERTHERESAXX
Encypted Message: AAHXIGPPLJEROLR
Decrypted Message: MOTHERTHERESAXX

F:\bin>java hillcipher
Enter the Plain text for Encryption:
hilcipher
Padded Text:HILCIPHER
Encypted Message: TIIWGHXIG
Decrypted Message: HILCIPHER

RESULT:
Thus the Hill cipher substitution technique was implemented and executed
successfully.
Ex.No. : 2a RAIL FENCE CIPHER
Date :

AIM:
To implement a rail fence transposition technique in Java.

ALGORITHM :
1. In the rail fence cipher, the plaintext is written downwards and diagonally on
successive "rails" of an imaginary fence, then moving up when we reach the bottom
rail.
2. When we reach the top rail, the message is written downwards again until the whole
plaintext is written out.
3. The message is then read off in rows.

PROGRAM:
class railfenceCipherHelper
{
int depth;
String encode(String msg, int depth) throws Exception
{
int r = depth;
int l = msg.length();
int c = l / depth;
int k = 0;
char mat[][] = new char[r][c];
String enc = "";
for (int i = 0; i< c; i++)
{
for (int j = 0; j < r; j++)
{
if (k != l)
{ mat[j][i] = msg.charAt(k++); }
else
{ mat[j][i] = 'X'; }
}}
for (int i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
{
enc += mat[i][j];
}}
return enc;
}
String decode(String encmsg, int depth) throws Exception
{
int r = depth;
int l = encmsg.length();
int c = l / depth;
int k = 0;
char mat[][] = new char[r][c];
String dec = "";
for (int i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
{
mat[i][j] = encmsg.charAt(k++);
}}
for (int i = 0; i< c; i++)
{
for (int j = 0; j < r; j++)
{
dec += mat[j][i];
}}
return dec;
}}
class railfencecipher
{
public static void main(String[] args) throws java.lang.Exception
{
railfenceCipherHelper rf = new railfenceCipherHelper();
String msg, enc, dec;
System.out.println("Enter the Plain text: ");
msg = System.console().readLine();
int depth = 2;
enc = rf.encode(msg, depth);
dec = rf.decode(enc, depth);
System.out.println("Plain Text:"+msg);
System.out.println("Encrypted Message-Cipher Text:"+enc);
System.out.printf("Decrypted Message-:"+dec);
}
}

OUTPUT:
F:\bin>javac railfencecipher.java
F:\bin>java railfencecipher
Enter the Plain text:
paulinefreeda
Plain Text:paulinefreeda
Encrypted Message-Cipher Text:puiereaalnfed
Decrypted Message-:paulinefreeda

RESULT:
Thus the Rail Fence Transposition Technique was implemented and executed
successfully.
Ex.No. : 2b ROW AND COLUMN TRANSFORMATION TECHNIQUE
Date :

AIM:
To implement a rail fence transposition technique in Java.

ALGORITHM:
1. Consider the plain text hello world, and let us apply the simple columnar transposition
technique as shown below

h e l l
o w o r
l d

2. The plain text characters are placed horizontally and the cipher text is created with
vertical format as: holewdlo lr.
3. Now, the receiver has to use the same table to decrypt the cipher text to plain text.

EXAMPLE:

PROGRAM:
import java.util.*;
class TransCipher {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the plain text");
String pl = sc.nextLine();
sc.close();
String s = "";
int start = 0;
for (int i= 0; i< pl.length(); i++) {
if (pl.charAt(i) == ' ') {
s = s + pl.substring(start, i);
start = i + 1;
}
}
s = s + pl.substring(start);
System.out.print(s);
System.out.println();
// end of space deletion
int k = s.length();
int l = 0;
int col = 4;
int row = s.length() / col;
char ch[][] = new char[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (l < k) {
ch[i][j] = s.charAt(l);
l++;
} else {
ch[i][j] = '#';
}
}
}
char trans[][] = new char[col][row];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
trans[j][i] = ch[i][j];
}}
for (int i = 0; i < col; i++) {
for (int j = 0; j < row; j++) {
System.out.print(trans[i][j]);
}}
System.out.println();
}
}

OUTPUT:
F:\bin>javac TransCipher.java
F:\bin>java TransCipher
Enter the plain text
altrozcarshervin
altrozcarshervin
aorrlzsvtchiraen
a l t r
o z c a
r s h e
r v I n

RESULT:
Thus the Row and Column Transposition Technique was implemented and executed
successfully.
Ex.No. : 3 DATA ENCRYPTION STANDARD (DES)
Date :

AIM:
To apply Data Encryption Standard (DES) Algorithm for a practical application like
User Message Encryption.

ALGORITHM:
1. Create a DES Key.
2. Create a Cipher instance from Cipher class, specify the following information
and separated by a slash (/).
 Algorithm name
 Mode (optional)
 Padding scheme (optional)
3. Convert String into Byte[] array format.
4. Make Cipher in encrypt mode, and encrypt it with Cipher.doFinal() method.
5. Make Cipher in decrypt mode, and decrypt it with Cipher.doFinal() method.

PROGRAM:
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,encryptedata,decryptedmessage;
public DES()
{
try
{
generatesymmetrickey();
inputmessage=JOptionPane.showInputDialog(null,"Enter message to
encrypt:");
byte[] ibyte =inputmessage.getBytes();
byte[] ebyte=encrypt(raw, ibyte);
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);
System.out.println("DES
SymmerticKey="+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


{
SecretKey seckey = new SecretKeySpec(raw, "DES");
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE,seckey);
byte[] encrypted=cipher.doFinal(clear);
return encrypted;
}

private static byte[] decrypt(byte[] raw,byte[] encrypted) throws Exception


{
SecretKey seckey = new SecretKeySpec(raw, "DES");
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE,seckey);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
public static void main(String args[])
{
DES des=new DES();
}

OUTPUT:

RESULT:
Thus the java program for applying Data Encryption Standard (DES) Algorithm for a
practical application of User Message Encryption is written and executed successfully.
Ex.No. : 4 AES ALGORITHM
Date :

AIM:
To apply Advanced Encryption Standard (AES) Algorithm for a practical application
like URL Encryption.

ALGORITHM:
1. AES is based on a design principle known as a substitution–permutation.
2. AES does not use a Feistel network like DES, it uses variant of Rijndael.
3. It has a fixed block size of 128 bits, and a key size of 128, 192, or 256 bits.
4. AES operates on a 4 × 4 column- major order array of bytes, termed the state

PROGRAM:
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AES


{
private static SecretKeySpec secretKey;
private static byte[] key;
public static void setKey(String myKey) {
MessageDigest sha = null;
try {
key = myKey.getBytes("UTF-8");
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
secretKey = new SecretKeySpec(key, "AES");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
public static String encrypt(String strToEncrypt, String secret) {
try {
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes
("UTF-8")));
} catch (Exception e) {
System.out.println("Error while encrypting: " + e.toString());
}
return null;
}

public static String decrypt(String strToDecrypt, String secret) {


try {
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
} catch (Exception e) {
System.out.println("Error while decrypting: " + e.toString());
}
return null;
}

public static void main(String[] args) {

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


String secretKey = System.console().readLine();

System.out.println("Enter the original URL: ");


String originalString = System.console().readLine();

String encryptedString = AES.encrypt(originalString, secretKey);


String decryptedString = AES.decrypt(encryptedString, secretKey);

System.out.println("URL Encryption Using AES Algorithm\n ------------ ");


System.out.println("Original URL : " + originalString);
System.out.println("Encrypted URL : " + encryptedString);
System.out.println("Decrypted URL : " + decryptedString);
}
}

OUTPUT:
C:\Security Lab New\programs>java AES
Enter the secret key:
annaUniversity
Enter the original URL:
www.annauniv.edu
URL Encryption Using AES Algorithm
Original URL : www.annauniv.edu
Encrypted URL : vibpFJW6Cvs5Y+L7t4N6YWWe07+JzS1d3CU2h3mEvEg=
Decrypted URL : www.annauniv.edu
RESULT:
Thus the java program for applying Advanced Encryption Standard (AES) Algorithm
for a practical application of URL encryption is written and executed successfully.
Ex.No. : 5 RSA ALGORITHM
Date :

AIM:
To implement a RSA algorithm using HTML and Javascript.

ALGORITHM:
1. Choose two prime number p and q.
2. Compute the value of n and t.
3. Find the value of public key e.
4. Compute the value of private key d.
5. Do the encryption and decryption
a. Encryption is given as,
c = te mod n
b. Decryption is given as,
t = cd mod n

PROGRAM:
rsa.html
<html>
<head>
<title>RSA Encryption</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<center>
<h1>RSA Algorithm</h1>
<h2>Implemented Using HTML & Javascript</h2>
<hr>
<table>
<tr>
<td>Enter First Prime Number:</td>
<td><input type="number" value="53" id="p"></td>
</tr>
<tr>
<td>Enter Second Prime Number:</td>
<td><input type="number" value="59" id="q"></p> </td>
</tr>
<tr>
<td>Enter the Message(cipher text):<br>[A=1, B=2,...]</td>
<td><input type="number" value="89" id="msg"></p> </td>
</tr>
<tr>
<td>Public Key:</td>
<td><p id="publickey"></p> </td>
</tr>
<tr>
<td>Exponent:</td>
<td><p id="exponent"></p> </td>
</tr>
<tr>
<td>Private Key:</td>
<td><p id="privatekey"></p></td>
</tr>
<tr>
<td>Cipher Text:</td>
<td><p id="ciphertext"></p> </td>
</tr>
<tr>
<td><button onclick="RSA();">Apply RSA</button></td>
</tr>
</table> </center>
</body>
<script type="text/javascript">

function RSA()
{
var gcd, p, q, no, n, t, e, i, x;
gcd = function (a, b) { return (!b) ? a : gcd(b, a % b); };
p = document.getElementById('p' ).value;
q = document.getElementById('q').value;
no = document.getElementById('msg').value;
n = p * q;
t = (p - 1) * (q - 1);
for (e = 2; e < t; e++)
{
if (gcd(e, t) == 1)
{
break;
}
}
for (i = 0; i < 10; i++)
{
x = 1 + i* t
if (x % e == 0)
{
d = x / e;
break;
}
}
ctt = Math.pow(no, e).toFixed(0);
ct = ctt % n;
dtt = Math.pow(ct, d).toFixed(0);
dt = dtt % n;
document.getElementById('publickey').innerHTML = n;
document.getElementById('exponent').innerHTML = e;
document.getElementById('privatekey').innerHTML = d;
document.getElementById('ciphertext').innerHTML = ct;
}
</script>
</html>

OUTPUT:

RESULT:
Thus the RSA algorithm was implemented using HTML and Javascript and executed
successfully.
Ex.No. : 6 DIFFIE-HELLMAN KEY EXCHANGE ALGORITHM
Date :

AIM:
To implement a Diffie-Hellman Key Exchange algorithm.

ALGORITHM:
1. Sender and receiver publicly agree to use a modulus p and base g which is a primitive
root modulo p.
2. Sender chooses a secret integer x then sends Bob R1 = gx mod p
3. Receiver chooses a secret integer y, then sends Alice R2 = gy mod p
4. Sender computes k1 = Bx mod p
5. Receiver computes k2 = Ay mod p
6. Sender and Receiver now share a secret key.

PROGRAM:
import java.io.*;
import java.math.BigInteger;
class dh
{
public static void main(String[]args)throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter prime number:");
BigInteger p=new BigInteger(br.readLine());

System.out.print("Enter primitive root of "+p+":");


BigInteger g=new BigInteger(br.readLine());

System.out.println("Enter value for x less than "+p+":");


BigInteger x=new BigInteger(br.readLine());
BigInteger R1=g.modPow(x,p);
System.out.println("R1="+R1);

System.out.print("Enter value for y less than "+p+":");


BigInteger y=new BigInteger(br.readLine());
BigInteger R2=g.modPow(y,p);
System.out.println("R2="+R2);

BigInteger k1=R2.modPow(x,p);
System.out.println("Key calculated at Sender's side:"+k1);
BigInteger k2=R1.modPow(y,p);
System.out.println("Key calculated at Receiver's side:"+k2);
System.out.println("Diffie-Hellman secret key was calculated.");
}
}
OUTPUT
C:\Security Lab New\programs>javac dh.java

C:\Security Lab New\programs>java dh


Enter prime number:
11
Enter primitive root of 11:7
Enter value for x less than 11:
3
R1=2
Enter value for y less than 11:6
R2=4
Key calculated at Sender's side:9
Key calculated at Receiver's side:9
Diffie-Hellman secret key was calculated.

RESULT:
Thus the Diffie-Hellman key exchange algorithm was implemented and executed
successfully.
Ex.No. : 7 SHA-1 ALGORITHM
Date :

AIM:
To calculate the message digest of a text using the SHA-1 algorithm in Java.
ALGORITHM:
1. Append Padding bits.
2. Append Length - 64 bits are appended to the end.
3. Prepare Processing Functions.
4. Prepare Processing Constants.
5. Initialize Buffers.
6. Processing Message in 512-bit blocks (L blocks in total message).
PROGRAM:
import java.util.Scanner;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class sha1
{
public static void main(String[] args)throws NoSuchAlgorithmException
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the String:");
String message = new String();
message = sc.next();
System.out.println("Mesage Digest is=");
System.out.println(sha1(message));
}
static String sha1(String input)throws NoSuchAlgorithmException
{
MessageDigest mDigest = MessageDigest.getInstance("SHA1");
byte[] result = mDigest.digest(input.getBytes());
StringBuffer sb = new StringBuffer();
for(int i = 0;i<result.length;i++)
{
sb.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
}
OUTPUT:
C:\Security Lab New\programs>java sha1
Enter the String:
CORONA VIRUS DISEASE
Mesage Digest is=
7690b7ccb987f4b3f32d2b9e7e8a69db2d0ded02

RESULT:
Thus the Secure Hash Algorithm (SHA-1) has been implemented and executed
successfully.
Ex.No. : 8 MD-5 ALGORITHM
Date :

AIM:
Calculate the message digest of a text using the MD-5 algorithm in JAVA.

ALGORITHM:

1. Read the 128-bit plain text


2. Divide into four blocks of 32 bits named as A,B,C,D.
3. Prepare Processing Functions.
4. Prepare Processing Constants.
5. Initialize Buffers.
6. Processing Message in 512-bit blocks (L blocks in total message).
PROGRAM:
import java.security.*;
public class MD5 {
public static void main(String[] a) {
// TODO code application logic here try
{
MessageDigest md = MessageDigest.getInstance("MD5");
System.out.println("Message digest object info: ");
System.out.println(" Algorithm = " +md.getAlgorithm());
System.out.println(" Provider = " +md.getProvider());
System.out.println(" ToString = " +md.toString());
String input = "";
md.update(input.getBytes());
byte[] output = md.digest();
System.out.println();
System.out.println("MD5(\""+input+"\") = "+bytesToHex(output));
input = "abc";
md.update(input.getBytes());
output = md.digest();
System.out.println();
System.out.println("MD5(\""+input+"\") = "
+bytesToHex(output));
input = "abcdefghijklmnopqrstuvwxyz";
md.update(input.getBytes());
output = md.digest();
System.out.println();
System.out.println("MD5(\"" +input+"\") =
"+bytesToHex(output));
System.out.println("");
}
catch (Exception e)
{
System.out.println("Exception: " +e);
}}
public static String bytesToHex(byte[] b)
{
char hexDigit[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C',
'D','E', 'F'};
StringBufferbuf = new StringBuffer();
for (int j=0; j> 4) & 0x0f]);
buf.append(hexDigit[b[j] & 0x0f]);
}
return buf.toString(); } }

OUTPUT:

Message digest object info: Algorithm = MD5


Provider = SUN version 1.6 ToString = MD5
Message Digest from SUN, MD5("") =
D41D8CD98F00B204E9800998ECF8427E
MD5("abc") =
900150983CD24FB0D6963F7D28E17F72
MD5("abcdefghijklmnopqrstuvwxyz") =
C3FCD3D76192E4007DFB496CCA67E13B

RESULT:
Thus the Message Digest Algorithm (MD-5) has been implemented and executed
successfully.
Ex.No. : 9 DIGITAL SIGNATURE SCHEME
Date :

AIM:
To implement the signature scheme - Digital Signature Standard.

ALGORITHM:
1. Declare the class and required variables.
2. Create the object for the class in the main program.
3. Access the member functions using the objects.
4. Implement the SIGNATURE SCHEME - Digital Signature Standard.
5. It uses a hash function.
6. The hash code is provided as input to a signature function along with a random
number K generated for the particular signature.
7. The signature function also depends on the sender„s private key.
8. The signature consists of two components.
9. The hash code of the incoming message is generated.
10. The hash code and signature are given as input to a verification function.
PROGRAM:
import java.util.*;
import java.math.BigInteger;
class dsaAlg {
final static BigInteger one = new BigInteger("1");
final static BigInteger zero = new BigInteger("0");
public static BigInteger getNextPrime(String ans)
{
BigInteger test = new BigInteger(ans);
while (!test.isProbablePrime(99))
e:
{
test = test.add(one);
}
return test;
}
public static BigInteger findQ(BigInteger n)
{
BigInteger start = new BigInteger("2");
while (!n.isProbablePrime(99))
{
while (!((n.mod(start)).equals(zero)))
{
start = start.add(one);
}
n = n.divide(start);
}
return n;
}
public static BigInteger getGen(BigInteger p, BigInteger q,
Random r)
{
BigInteger h = new BigInteger(p.bitLength(), r);
h = h.mod(p);
return h.modPow((p.subtract(one)).divide(q), p);
}
public static void main (String[] args) throws
java.lang.Exception
{
Random randObj = new Random();
BigInteger p = getNextPrime("10600"); /* approximate
prime */
BigInteger q = findQ(p.subtract(one));
BigInteger g = getGen(p,q,randObj);
System.out.println(" \n simulation of Digital Signature Algorithm \n");
System.out.println(" \n global public key components are:\n");
System.out.println("\np is: " + p);
System.out.println("\nq is: " + q);
System.out.println("\ng is: " + g);
BigInteger x = new BigInteger(q.bitLength(), randObj);
x = x.mod(q);
BigInteger y = g.modPow(x,p);
BigInteger k = new BigInteger(q.bitLength(), randObj);
k = k.mod(q);
BigInteger r = (g.modPow(k,p)).mod(q);
BigInteger hashVal = new BigInteger(p.bitLength(),
randObj);
BigInteger kInv = k.modInverse(q);
BigInteger s = kInv.multiply(hashVal.add(x.multiply(r)));
s = s.mod(q);
System.out.println("\nsecret information are:\n");
System.out.println("x (private) is:" + x);
System.out.println("k (secret) is: " + k);
System.out.println("y (public) is: " + y);
System.out.println("h (rndhash) is: " + hashVal);
System.out.println("\n generating digital signature:\n");
System.out.println("r is : " + r);
System.out.println("s is : " + s);
BigInteger w = s.modInverse(q);
BigInteger u1 = (hashVal.multiply(w)).mod(q);
BigInteger u2 = (r.multiply(w)).mod(q);
BigInteger v = (g.modPow(u1,p)).multiply(y.modPow(u2,p));
v = (v.mod(p)).mod(q);
System.out.println("\nverifying digital signature (checkpoints)\n:");
System.out.println("w is : " + w);
System.out.println("u1 is : " + u1);
System.out.println("u2 is : " + u2);
System.out.println("v is : " + v);
if (v.equals(r))
{
System.out.println("\nsuccess: digital signature is verified!\n " + r);
}
else
{
System.out.println("\n error: incorrect digital signature\n ");
}
}
}

OUTPUT:

C:\Security Lab New\programs>javac dsaAlg.java


C:\Security Lab New\programs>java dsaAlg
simulation of Digital Signature Algorithm
global public key components are:
p is: 10601
q is: 53
g is: 6089
secret information are:
x (private) is:6
k (secret) is: 3
y (public) is: 1356
h (rndhash) is: 12619
generating digital signature:
r is : 2
s is : 41
verifying digital signature (checkpoints):
w is : 22
u1 is : 4
u2 is : 44
v is : 2
success: digital signature is verified!
2

RESULT:
Thus the Digital Signature Standard Signature Scheme has been implemented and
executed successfully.
CONTENT BEYOND

THE SYLLABUS
Ex. No. : 10 INTRUSION DETECTION SYSTEM (IDS)

Date:

AIM:
To demonstrate Intrusion Detection System (IDS) using Snort software tool.

STEPS ON CONFIGURING AND INTRUSION DETECTION

1. Download Snort from the Snort.org website. (http://www.snort.org/snort-downloads)


2. Download Rules(https://www.snort.org/snort-rules). You must register to get the rules.
(You should download these often)
3. Double click on the .exe to install snort. This will install snort in the “C:\Snort” folder.It is
important to have WinPcap (https://www.winpcap.org/install/) installed
4. Extract the Rules file. You will need WinRAR for the .gz file.
5. Copy all files from the “rules” folder of the extracted folder. Now paste the rules into
“C:\Snort\rules” folder.
6. Copy “snort.conf” file from the “etc” folder of the extracted folder. You must paste it into
“C:\Snort\etc” folder. Overwrite any existing file. Remember if you modify your
snort.conf file and download a new file, you must modify it for Snort to work.
7. Open a command prompt (cmd.exe) and navigate to folder “C:\Snort\bin” folder. ( at the
Prompt, type cd\snort\bin)
8. To start (execute) snort in sniffer mode use following command:
snort -dev -i 3
-i indicates the interface number. You must pick the correct interface number. In my case, it
is 3.
-dev is used to run snort to capture packets on your network.

To check the interface list, use following command:


snort -W
Finding an interface

You can tell which interface to use by looking at the Index number and finding Microsoft.
As you can see in the above example, the other interfaces are for VMWare. My interface is
3.

9. To run snort in IDS mode, you will need to configure the file “snort.conf” according to
your network environment.
10. To specify the network address that you want to protect in snort.conf file, look for the
following line.
var HOME_NET 192.168.1.0/24 (You will normally see any here)
11. You may also want to set the addresses of DNS_SERVERS, if you have some on your
network.

Example:

example snort
12. Change the RULE_PATH variable to the path of rules folder.
var RULE_PATH c:\snort\rules

path to rules
13. Change the path of all library files with the name and path on your system. and you must
change the path of snort_dynamicpreprocessorvariable.
C:\Snort\lib\snort_dynamiccpreprocessor
You need to do this to all library files in the “C:\Snort\lib” folder. The old path might be:
“/usr/local/lib/…”. you will need to replace that path with your system path. Using
C:\Snort\lib
14. Change the path ofthe “dynamicengine” variable value in the “snort.conf” file..
Example:
dynamicengine C:\Snort\lib\snort_dynamicengine\sf_engine.dll

15 Add the paths for “include classification.config” and “include reference.config” files.
include c:\snort\etc\classification.config
include c:\snort\etc\reference.config
16. Remove the comment (#) on the line to allow ICMP rules, if it is commented with a #.
include $RULE_PATH/icmp.rules
17. You can also remove the comment of ICMP-info rules comment, if it is commented.
include $RULE_PATH/icmp- info.rules
18. To add log files to store alerts generated by snort, search for the “output log” test in
snort.conf and add the following line:
output alert_fast: snort-alerts.ids
19. Comment (add a #) the whitelist $WHITE_LIST_PATH/white_list.rules and the
blacklist

Change the nested_ip inner , \ to nested_ip inner #, \


20. Comment out (#) following lines:
#preprocessor normalize_ip4
#preprocessor normalize_tcp: ips ecn stream
#preprocessor normalize_icmp4
#preprocessor normalize_ip6
#preprocessor normalize_icmp6

21. Save the “snort.conf” file.


22. To start snort in IDS mode, run the following command:

snort -c c:\snort\etc\snort.conf - l c:\snort\log - i 3


(Note: 3 is used for my interface card)

Ifa log is created, select the appropriate program to open it. You can use WordPard or
NotePad++ to read the file.

To generate Log files in ASCII mode, you can use following command while running snort in
IDS mode:
snort -A console - i3 -c c:\Snort\etc\snort.conf -l c:\Snort\log -K ascii

23. Scan the computer that is running snort from another computer by using PING or NMap
(ZenMap).

After scanning or during the scan you can check the snort-alerts.ids file in the log folder to
insure it is logging properly. You will see IP address folders appear.

Snort monitoring traffic –


RESULT:
Thus the Intrusion Detection System(IDS) has been demonstrated using the Open
Source Intrusion Detection Tool Snort.
Ex. No. : 11 BLOWFISH ALGORITHM

Date

Aim:
Write a JAVA program to implement the BlowFish algorithm logic

Theory:
Blowfish is a symmetric-key block cipher that uses a variable-length key. It operates on 64-bit
blocks of data and can use keys between 32 bits and 448 bits in length.

Program:

import java.nio.ByteBuffer;

public class Blowfish {

private static final int BLOCK_SIZE = 8; // 64 bits = 8 bytes


private static final int P_ARRAY_SIZE = 18;
private static final int S_ARRAY_SIZE = 4 * 256;

private static final int[] P = new int[P_ARRAY_SIZE];


private static final int[] S = new int[S_ARRAY_SIZE];

static {
// Initialize P-array and S-array with predefined values (for simplification, initialize with
example values)
// These should be filled with proper values as per the Blowfish specification
// For example, P-array and S-array should be filled with specific values from Blowfish's
standard
// This can be done manually or read from predefined data in a production
implementation.
}

private int[] pArray;


private int[] sArray;

public Blowfish(byte[] key) {


// Key expansion logic
this.pArray = P.clone();
this.sArray = S.clone();
keyExpansion(key);
}

private void keyExpansion(byte[] key) {


int keyIndex = 0;
for (int i = 0; i < P_ARRAY_SIZE; i++) {
int value = 0;
for (int j = 0; j < 4; j++) {
value = (value << 8) | (key[keyIndex] & 0xFF);
keyIndex = (keyIndex + 1) % key.length;
}
pArray[i] ^= value;
}
// Perform an initial encryption cycle to generate the S-array.
int[] temp = new int[2];
for (int i = 0; i < P_ARRAY_SIZE; i += 2) {
encryptBlock(temp);
pArray[i] = temp[0];
pArray[i + 1] = temp[1];
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 256; j += 2) {
encryptBlock(temp);
sArray[i * 256 + j] = temp[0];
sArray[i * 256 + j + 1] = temp[1];
}
}
}

private void encryptBlock(int[] block) {


int left = block[0];
int right = block[1];

left ^= pArray[0];
for (int i = 1; i < P_ARRAY_SIZE; i += 2) {
right ^= f(left) ^ pArray[i];
left ^= f(right) ^ pArray[i + 1];
}

block[0] = right ^ pArray[P_ARRAY_SIZE - 2];


block[1] = left ^ pArray[P_ARRAY_SIZE - 1];
}

private int f(int x) {


int a = (x >> 24) & 0xFF;
int b = (x >> 16) & 0xFF;
int c = (x >> 8) & 0xFF;
int d = x & 0xFF;
return ((sArray[a] + sArray[256 + b]) ^ sArray[512 + c]) + sArray[768 + d];
}

public byte[] encrypt(byte[] data) {


ByteBuffer buffer = ByteBuffer.wrap(data);
int blockCount = (data.length + BLOCK_SIZE - 1) / BLOCK_SIZE;

byte[] encryptedData = new byte[blockCount * BLOCK_SIZE];


for (int i = 0; i < blockCount; i++) {
int[] block = new int[2];
block[0] = buffer.getInt();
block[1] = buffer.getInt();

encryptBlock(block);
encryptedData[i * BLOCK_SIZE] = (byte) (block[0] >> 24);
encryptedData[i * BLOCK_SIZE + 1] = (byte) (block[0] >> 16);
encryptedData[i * BLOCK_SIZE + 2] = (byte) (block[0] >> 8);
encryptedData[i * BLOCK_SIZE + 3] = (byte) (block[0]);
encryptedData[i * BLOCK_SIZE + 4] = (byte) (block[1] >> 24);
encryptedData[i * BLOCK_SIZE + 5] = (byte) (block[1] >> 16);
encryptedData[i * BLOCK_SIZE + 6] = (byte) (block[1] >> 8);
encryptedData[i * BLOCK_SIZE + 7] = (byte) (block[1]);
}

return encryptedData;
}

public byte[] decrypt(byte[] data) {


ByteBuffer buffer = ByteBuffer.wrap(data);
int blockCount = data.length / BLOCK_SIZE;

byte[] decryptedData = new byte[data.length];


for (int i = 0; i < blockCount; i++) {
int[] block = new int[2];
block[0] = buffer.getInt();
block[1] = buffer.getInt();

decryptBlock(block);
decryptedData[i * BLOCK_SIZE] = (byte) (block[0] >> 24);
decryptedData[i * BLOCK_SIZE + 1] = (byte) (block[0] >> 16);
decryptedData[i * BLOCK_SIZE + 2] = (byte) (block[0] >> 8);
decryptedData[i * BLOCK_SIZE + 3] = (byte) (block[0]);
decryptedData[i * BLOCK_SIZE + 4] = (byte) (block[1] >> 24);
decryptedData[i * BLOCK_SIZE + 5] = (byte) (block[1] >> 16);
decryptedData[i * BLOCK_SIZE + 6] = (byte) (block[1] >> 8);
decryptedData[i * BLOCK_SIZE + 7] = (byte) (block[1]);
}

return decryptedData;
}

private void decryptBlock(int[] block) {


int left = block[0];
int right = block[1];

left ^= pArray[P_ARRAY_SIZE - 2];


for (int i = P_ARRAY_SIZE - 3; i > 0; i -= 2) {
right ^= f(left) ^ pArray[i];
left ^= f(right) ^ pArray[i - 1];
}

block[0] = right ^ pArray[1];


block[1] = left ^ pArray[0];
}

public static void main(String[] args) {


// Example usage
byte[] key = "secretkey".getBytes(); // Blowfish key (you can modify it)
Blowfish blowfish = new Blowfish(key);

byte[] data = "HelloWorld".getBytes(); // Message to encrypt


System.out.println("Original Data: " + new String(data));

// Encrypting data
byte[] encrypted = blowfish.encrypt(data);
System.out.println("Encrypted Data (Base64 encoded): " + bytesToHex(encrypted));

// Decrypting data
byte[] decrypted = blowfish.decrypt(encrypted);
System.out.println("Decrypted Data: " + new String(decrypted));
}

// Helper method to convert byte array to hex string for easy visualization
private static String bytesToHex(byte[] bytes) {
StringBuilder hex = new StringBuilder();
for (byte b : bytes) {
hex.append(String.format("%02X ", b));
}
return hex.toString().trim();
}
}

OUTPUT:

Original Data: HelloWorld


Encrypted Data (Base64 encoded): 54B90E42 59D46B3A C2D0B12B FBD2E16F
Decrypted Data: HelloWorld

RESULT:
Thus the BlowFish algorithm logic has been implemented and executed successful.

You might also like