0% found this document useful (0 votes)
9 views67 pages

Is Lab Manual1

The document is a laboratory manual for the Information Security course (3170720) for B.E. Semester 7 Computer Engineering students. It outlines the objectives, practical experiments, and expected outcomes related to cryptography and data security, emphasizing hands-on experience and industry-relevant skills. The manual includes guidelines for both faculty and students, safety instructions, and a course outcome matrix for various cryptographic techniques and algorithms.

Uploaded by

Neeraj Nair
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)
9 views67 pages

Is Lab Manual1

The document is a laboratory manual for the Information Security course (3170720) for B.E. Semester 7 Computer Engineering students. It outlines the objectives, practical experiments, and expected outcomes related to cryptography and data security, emphasizing hands-on experience and industry-relevant skills. The manual includes guidelines for both faculty and students, safety instructions, and a course outcome matrix for various cryptographic techniques and algorithms.

Uploaded by

Neeraj Nair
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/ 67

A Laboratory Manual for

Information Security
(3170720)

B.E. Semester 7
(Computer Engineering)

Institute logo

Directorate of Technical Education,Gandhinagar,Gujarat


210180107028 Information Security (3170720)

Institute Name

Certificate
This is to certify thatMr./Ms. ___________________________________
________ Enrollment No. _______________ of B.E. Semester
_____Computer Engineering of this Institute (GTU Code: _____ ) has
satisfactorily completed the Practical / Tutorial work for the subject
Information Security (3170720) for the academic year 2022-23.

Place: __________
Date: __________

Name and Sign of Faculty member

Head of the Department


210180107028 Information Security (3170720)

Preface

Main motto of any laboratory/practical/field work is for enhancing required skills as well as
creating ability amongst students to solve real time problem by developing relevant
competencies in psychomotor domain.By keeping in view, GTU has designed competency
focused outcome-based curriculum for engineering degree programs where sufficient weightage
is given to practical work. It shows importance of enhancement of skills amongst the students
and it pays attention to utilize every second of time allotted for practical amongst students,
instructors and faculty members to achieve relevant outcomes by performing the experiments
rather than having merely study type experiments. It is must for effective implementation of
competency focused outcome-basedcurriculum that every practical is keenly designed to serve as
a tool to develop and enhance relevant competency required by the various industry among every
student. These psychomotor skills are very difficult to develop through traditional chalk and
board content delivery method in the classroom. Accordingly, this lab manual is designed to
focus on the industry defined relevant outcomes, rather than old practice of conducting practical
to prove concept and theory.

By using this lab manual students can go through the relevant theory and procedure in advance
before the actual performance which creates an interest and students can have basic idea prior to
performance. This in turn enhances pre-determined outcomes amongst students. Each
experiment in this manual begins with competency, industry relevant skills, course outcomes as
well as practical outcomes (objectives). The students will also achieve safety and necessary
precautions to be taken while performing practical.

This manual also provides guidelines to faculty members to facilitate student centric lab
activities through each experiment by arranging and managing necessary resources in order that
the students follow the procedures with required safety and necessary precautions to achieve the
outcomes. It also gives an idea that how students will be assessed by providing rubrics.

Information security is the subject that helps students to understand various aspects of data
security. It provides a way to know various kinds of breaches that happen with data and how to
eliminate them using various techniques. The student is also able to learn various methodologies
which used by current used by developers to achieve the security of information.

.
210180107028 Information Security (3170720)

Practical – Course Outcome matrix

Course Outcomes (COs):


1. Explore the basic principles of the symmetric cryptography and techniques with
their strengths and weaknesses from perspective of cryptanalysis
2. Implement and analyze various symmetric key cryptography algorithms and their
application in different context
3. Compare public key cryptography with private key cryptography and Implement
various asymmetric key cryptography algorithms
4. Explore the concept of hashing and implement various hashing algorithms for
message integrity
5. Explore and use the techniques and standards of digital signature, key management
and authentication
Sr. CO CO CO CO CO
Objective(s) of Experiment
No. 1 2 3 4 5

1. Implement Caesar cipher encryption-decryption. √

2. Implement Playfair cipher encryption-decryption. √

3. Implement Hill cipher encryption-decryption √

4. Implement Vigenere Cipher encryption-decryption √

Implement Rail Fence Transposition cipher


5. √
technique.

6. To implement Simple DES encryption-decryption. √

7. To implement Simple AES encryption-decryption. √

8. Implement RSA encryption-decryption algorithm. √

9. Implement Diffi-Hellman Key exchange Method √

10. Write a program to generate MD-5 hash. √

11. Write a program to generate SHA-1 hash √

12. Implement a digital signature algorithm. √

13. Demonstrate how to work with JCrypTool

14. Demonstrate how to work with Wireshark


210180107028 Information Security (3170720)

Industry Relevant Skills

The following industry relevant competency are expected to be developed in the student by
undertaking the practical work of this laboratory.
1. Able to think about information security scenario and make solution
2. Able to develop and algorithms which helps to secure data

Guidelines for Faculty members


1. Teacher should provide the guideline with demonstration of practical to the students
with all features.
2. Teacher shall explain basic concepts/theory related to the experiment to the students before
starting of each practical
3. Involve all the students in performance of each experiment.
4. Teacher is expected to share the skills and competencies to be developed in the students
and ensure that the respective skills and competencies are developed in the students
after the completion of the experimentation.
5. Teachers should give opportunity to students for hands-on experience after the
demonstration.
6. Teacher may provide additional knowledge and skills to the students even though not
covered in the manual but are expected from the students by concerned industry.
7. Give practical assignment and assess the performance of students based on task
assigned to check whether it is as per the instructions or not.
8. Teacher is expected to refer complete curriculum of the course and follow the
guidelines for implementation.

Instructions for Students


1. Students are expected to carefully listen to all the theory classes delivered by the faculty
members and understand the COs, content of the course, teaching and examination
scheme, skill set to be developed etc.
2. Students shall organize the work in the group and make record of all observations.
3. Students shall develop maintenance skill as expected by industries.
4. Student shall attempt to develop related hand-on skills and build confidence.
5. Student shall develop the habits of evolving more ideas, innovations, skills etc. apart
from those included in scope of manual.
6. Student shall refer technical magazines and data books.
7. Student should develop a habit of submitting the experimentation work as per the
schedule and s/he should be well prepared for the same.

Common Safety Instructions

Students are expected to carefully


210180107028 Information Security (3170720)

Index
(Progressive Assessment Sheet)

Sr. Objective(s) of Experiment Page Date of Date of Assessme Sign. of Remar


No. No. perform submiss nt Teacher ks
ance ion Marks with date
Implement Caesar cipher encryption-
1
decryption.
Implement Playfair cipher encryption-
2
decryption.
Implement Hill cipher encryption-
3
decryption
Implement Vigenere Cipher encryption-
4
decryption
Implement Rail Fence Transposition cipher
5
technique.
To implement Simple DES encryption-
6
decryption.
To implement Simple AES encryption-
7
decryption.
Implement RSA encryption-decryption
8
algorithm.
Implement Diffi-Hellman Key exchange
9
Method

10 Write a program to generate MD-5 hash.

11 Write a program to generate SHA-1 hash

12 Implement a digital signature algorithm.

13 Demonstrate how to work with JCrypTool

14 Demonstrate how to work with Wireshark

Total

OBJECTIVES:
The student should be made to:

➢ Learn to implement the algorithms DES, RSA,MD5,SHA-1 Etc.


➢ Learn to use network security tools like crypto, Wireshark

OUTCOMES:
At the end of the course, the student should be able to:

➢ Implement various cipher techniques


210180107028 Information Security (3170720)

➢ Develop various security algorithms


➢ Use different open source tools for network security and analysis

LIST OF HARDWARE REQUIREMENTS & SOFTWARE REQUIREMENTS

SOFTWARE REQUIREMENTS

➢ C/ C++, JDK Etc. (As per requirement)

HARDWARE REQUIREMENTS

➢ Standalone desktops
210180107028 Information Security (3170720)

Experiment No: 1
Implementation of caesar cipher
Date:
Relevant CO: Explore the basic principles of the symmetric cryptography and techniques with their
strengths and weaknesses from perspective of cryptanalysis

Objectives: (a) to understand working fundamental of Caeser Cipher


(b) to carry out Implementation of Caesar cipher encryption-decryption.

Equipment/Instruments: Computer System, Turbo-c/ JDK


Theory:
To encrypt a message with a Caesar cipher, each letter in the message is changed
using a simple rule: shift by three. Each letter is replaced by the letter three letters ahead in
the alphabet. A becomes D, B becomes E, and so on. For the last letters, we can think of the
alphabet as a circle and "wrap around". W becomes Z, X becomes A, Y bec omes B, and Z
becomes C. To change a message back, each letter is replaced by the one three before it.

Example:

Algorithm:

STEP-1: Read the plain text from the user.


STEP-2: Read the key value from the user.
STEP-3: If the key is positive then encrypt the text by adding the key with each
character in the plain text.
STEP-4: Else subtract the key from the plain text.
STEP-5: Display the cipher text obtained above.

8|Page
210180107028 Information Security (3170720)

Program:

package Caesercipher;

import java.util.Scanner;

public class Casercipher {


static String alphabet = "abcdefghijklmnopqrstuvwxyz";

public static void main(String []args) {


Scanner sc = new Scanner(System.in);
System.out.print("Enter The Given Plain Text >>> ");
String pText = sc.nextLine();

System.out.print("Enter The Given Key >>> ");


int Key = sc.nextInt();

String ciphertext = encoding(pText,Key);


System.out.print("The Encoded Cipher Text is : "+ ciphertext);

System.out.print("\nThe Decodded Plain Text is : "+ decoding(ciphertext,Key));


}
public static String encoding(String pText,int Key) {
pText = pText.toLowerCase();
String cText = "";
for(int i=0; i<pText.length(); i++) {
int Charindex = alphabet.indexOf(pText.charAt(i));
int newindex = (Charindex + Key)%26;
char cipherchar = alphabet.charAt(newindex);
cText = cText + cipherchar;
}
return cText;
}
public static String decoding(String cText, int Key) {
cText = cText.toLowerCase();
String pText = "";
for(int i =0; i<cText.length(); i++) {
int Charindex = alphabet.indexOf(cText.charAt(i));
int newindex = (Charindex - Key)%26;
if(newindex<0) {
newindex = alphabet.length()+ newindex;
}
char plainchar = alphabet.charAt(newindex);
9|Page
210180107028 Information Security (3170720)

pText = pText + plainchar;


}
return pText;
}

Output:

Enter The Given Plain Text >>> alphabet


Enter The Given Key >>> 3
The Encoded Cipher Text is : doskdehw
The Decodded Plain Text is : alpha

Conclusion:

By Performing Experiment 1, We understand the working fundamental of Caeser Cipher to carry


out Implementation of Caesar cipher encryption-decryption.

Quiz:

1. Is Ceaser Cipher Symmetric or Asymmetrci algorithm ?

 Yes, the Caesar Cipher is a symmetric encryption algorithm

2. Encrypt the word alphabet using a Caesar cipher with a shift of 3

 Given Plain Text = alphabet


shift = 3
Encoded Cipher Text is = doskdehw

10 | P a g e
210180107028 Information Security (3170720)

Suggested Reference:
1. https://www.geeksforgeeks.org/caesar-cipher-in-cryptography/

References used by the students:

1. https://www.geeksforgeeks.org/caesar-cipher-in-cryptography/

Rubric wise marks obtained:

Rubrics 1 2 3 4 5 Total
Marks

11 | P a g e
210180107028 Information Security (3170720)

Experiment No: 2
Implementation of Playfair cipher
Date:
Relevant CO: Explore the basic principles of the symmetric cryptography and techniques with their
strengths and weaknesses from perspective of cryptanalysis

Objectives: (a) to understand working fundamental of Playfair cipher


(b) to carry out Implementation of Playfair cipher encryption-decryption.

Equipment/Instruments: Computer System, Turbo-c/ JDK


Theory:
The Playfair cipher starts with creating a key table. The key table is a 5×5 grid of
letters that will act as the key for encrypting your plaintext. Each of the 25 letters must be
unique and one letter of the alphabet is omitted from the table (as there are 25 spots and 26
letters in the alphabet). To encrypt a message, one would break the message into digrams
(groups of 2 letters) such that, for example, "HelloWorld" becomes "HE LL OW OR LD",
and map them out on the key table. The two letters of the diagram are considered as the
opposite corners of a rectangle in the key table. Note the relative position of the corners of
this rectangle. Thenapply the following 4 rules, in order, to each pair of letters in the plaintext:

1. If both letters are the same (or only one letter is left), add an "X" after the first letter
2. If the letters appear on the same row of your table, replace them with the letters to
their immediate right respectively
3. If the letters appear on the same column of your table, replace them with the letters
immediately below respectively

If the letters are not on the same row or column, replace them with the letters on the same row
respectively but at the other pair of corners of the rectangle defined by the original pair.

Example:

12 | P a g e
210180107028 Information Security (3170720)
Algorithm:

STEP-1: Read the plain text from the user.


STEP-2: Read the keyword from the user.
STEP-3: Arrange the keyword without duplicates in a 5*5 matrix in the row order and
fill the remaining cells with missed out letters in alphabetical order. Note that
‘i’ and ‘j’ takes the same cell.
STEP-4: Group the plain text in pairs and match the corresponding corner letters by
forming a rectangular grid.

STEP-5: Display the obtained cipher text.

Program:

package playfaircipher;

import java.awt.Point;
import java.util.Scanner;

public class PlayfairCipher {


private int length = 0;
private String[][] table;

public static void main(String[] args) {


new PlayfairCipher(); // Invoke the constructor
}

public PlayfairCipher() {
// Prompt user for the key
System.out.print("Enter the key for playfair cipher: ");
Scanner sc = new Scanner(System.in);
String key = parseString(sc);

while (key.equals("")) {
System.out.print("Key cannot be empty. Enter again: ");
key = parseString(sc);
}

// Generate cipher table


table = this.cipherTable(key);

// Prompt user for the plaintext


System.out.print("Enter the plaintext to be enciphered: ");
String input = parseString(sc);

13 | P a g e
210180107028 Information Security (3170720)

while (input.equals("")) {
System.out.print("Plaintext cannot be empty. Enter again: ");
input = parseString(sc);
}

// Encipher and then decode the message


String output = cipher(input);
String decodedOutput = decode(output);

// Output the results to the user


this.keyTable(table);
this.printResults(output, decodedOutput);
sc.close();
}

private String parseString(Scanner sc) {


String parse = sc.nextLine().toUpperCase().replaceAll("[^A-Z]", "");
parse = parse.replace("J", "I"); // Replace 'J' with 'I'
return parse;
}

private String[][] cipherTable(String key) {


String[][] playfairTable = new String[5][5];
String keyString = key + "ABCDEFGHIKLMNOPQRSTUVWXYZ";

// Fill string array with empty string


for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
playfairTable[i][j] = "";
}
}

for (int k = 0; k < keyString.length(); k++) {


boolean repeat = false;
boolean used = false;

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


for (int j = 0; j < 5; j++) {
if (playfairTable[i][j].equals("" + keyString.charAt(k))) {
repeat = true;
} else if (playfairTable[i][j].equals("") && !repeat && !used) {
playfairTable[i][j] = "" + keyString.charAt(k);
used = true;

14 | P a g e
210180107028 Information Security (3170720)

}
}
}
}
return playfairTable;
}

private String cipher(String in) {


// Insert 'X' between duplicate letters and handle odd length
length = (int) in.length() / 2 + in.length() % 2;

for (int i = 0; i < (length - 1); i++) {


if (in.charAt(2 * i) == in.charAt(2 * i + 1)) {
in = new StringBuffer(in).insert(2 * i + 1, 'X').toString();
length = (int) in.length() / 2 + in.length() % 2;
}
}

String[] digraph = new String[length];


for (int j = 0; j < length; j++) {
if (j == (length - 1) && in.length() / 2 == (length - 1)) {
in = in + "X";
}
digraph[j] = in.charAt(2 * j) + "" + in.charAt(2 * j + 1);
}

String[] encDigraphs = encodeDigraph(digraph);


StringBuilder out = new StringBuilder();

for (int k = 0; k < length; k++) {


out.append(encDigraphs[k]);
}

return out.toString();
}

private String[] encodeDigraph(String[] di) {


String[] encipher = new String[length];

for (int i = 0; i < length; i++) {


char a = di[i].charAt(0);
char b = di[i].charAt(1);

int r1 = (int) getPoint(a).getX();


int r2 = (int) getPoint(b).getX();

15 | P a g e
210180107028 Information Security (3170720)

int c1 = (int) getPoint(a).getY();


int c2 = (int) getPoint(b).getY();

if (r1 == r2) {
c1 = (c1 + 1) % 5;
c2 = (c2 + 1) % 5;
} else if (c1 == c2) {
r1 = (r1 + 1) % 5;
r2 = (r2 + 1) % 5;
} else {
int temp = c1;
c1 = c2;
c2 = temp;
}

encipher[i] = table[r1][c1] + "" + table[r2][c2];


}
return encipher;
}

private String decode(String out) {


StringBuilder decoded = new StringBuilder();

for (int i = 0; i < out.length() / 2; i++) {


char a = out.charAt(2 * i);
char b = out.charAt(2 * i + 1);

int r1 = (int) getPoint(a).getX();


int r2 = (int) getPoint(b).getX();
int c1 = (int) getPoint(a).getY();
int c2 = (int) getPoint(b).getY();

if (r1 == r2) {
c1 = (c1 + 4) % 5;
c2 = (c2 + 4) % 5;
} else if (c1 == c2) {
r1 = (r1 + 4) % 5;
r2 = (r2 + 4) % 5;
} else {
int temp = c1;
c1 = c2;
c2 = temp;
}

decoded.append(table[r1][c1]).append(table[r2][c2]);
16 | P a g e
210180107028 Information Security (3170720)

return decoded.toString();
}

private Point getPoint(char c) {


Point pt = new Point(0, 0);

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


for (int j = 0; j < 5; j++) {
if (c == table[i][j].charAt(0)) {
pt = new Point(i, j);
}
}
}

return pt;
}

private void keyTable(String[][] printTable) {


System.out.println("Playfair Cipher Key Matrix:");
System.out.println();

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


for (int j = 0; j < 5; j++) {
System.out.print(printTable[i][j] + " ");
}
System.out.println();
}

System.out.println();
}

private void printResults(String encipher, String dec) {


System.out.println("Encrypted Message: " + encipher);
System.out.println();
System.out.println("Decrypted Message: " + dec);
}
}

17 | P a g e
210180107028 Information Security (3170720)

Output:

Enter the key for playfair cipher: gaurav


Enter the plaintext to be enciphered: hello
Playfair Cipher Key Matrix:

G A U R V
B C D E F
H I K L M
N O P Q S
T W X Y Z

Encrypted Message: LBKYIQ

Decrypted Message: HELXLO

Conclusion:

By Performing Experiment 2, We understand the working fundamental of Playfair Cipher to carry


out Implementation of Playfair cipher encryption-decryption.

Quiz:

1. Playfair cipher is harder to crack than keyword cipher? True/False

 True, Playfair cipher is harder to crack than keyword cipher because of it’s encryption of double pair
letters.

Suggested Reference:
1. https://www.geeksforgeeks.org/playfair-cipher-with-examples/

References used by the students:

1. https://www.geeksforgeeks.org/playfair-cipher-with-examples/

Rubric wise marks obtained:

Rubrics 1 2 3 4 5 Total
Marks

18 | P a g e
210180107028 Information Security (3170720)

Experiment No: 3
Implementation of Hill cipher
Date:
Relevant CO: Explore the basic principles of the symmetric cryptography and techniques with their
strengths and weaknesses from perspective of cryptanalysis

Objectives: (a) to understand working fundamental of Hill Cipher


(b) to carry out Implementation of Hill cipher encryption-decryption.

Equipment/Instruments: Computer System, Turbo-c/ JDK


Theory:
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 is
multiplied by an invertible n × n matrix, against modulus 26. To decrypt the message, each block is
multiplied by the inverse of the m trix used for encryption. The matrix used for encryption is the
cipher key, and it sho ld be chosen randomly from the set of invertible n × n matrices (modulo 26).

Algorithm:

STEP-1: Read the plain text and key from the user.
STEP-2: Split the plain text into groups of length three.
STEP-3: Arrange the keyword in a 3*3 matrix.
STEP-4: Multiply the two matrices to obtain the cipher text of length three.
STEP-5: Combine all these groups to get the complete cipher text.

Program:

import java.util.ArrayList;
import java.util.Scanner;

public class HillCipherExample {

// Method to accept key matrix


private static int[][] getKeyMatrix() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter key matrix:");
String key = sc.nextLine();
double sq = Math.sqrt(key.length());

// Check if the key length forms a square matrix


if (sq != (long) sq) {
System.out.println("Cannot form a square matrix");
}

int len = (int) sq;

int[][] keyMatrix = new int[len][len];


int k = 0;

19 | P a g e
210180107028 Information Security (3170720)

for (int i = 0; i < len; i++) {


for (int j = 0; j < len; j++) {
keyMatrix[i][j] = ((int) key.charAt(k)) - 97;
k++;
}
}
return keyMatrix;
}

// Method to check whether the key matrix is valid (det != 0)


private static void isValidMatrix(int[][] keyMatrix) {
int det = keyMatrix[0][0] * keyMatrix[1][1] - keyMatrix[0][1] * keyMatrix[1][0];

// If det = 0, throw an exception and terminate


if (det == 0) {
throw new java.lang.Error("Det equals to zero, invalid key matrix!");
}
}

// Method to check if the reverse key matrix is valid (matrix mod 26 = (1,0,0,1))
private static void isValidReverseMatrix(int[][] keyMatrix, int[][] reverseMatrix) {
int[][] product = new int[2][2];

// Find the product matrix of key matrix times reverse key matrix
product[0][0] = (keyMatrix[0][0] * reverseMatrix[0][0] + keyMatrix[0][1] * reverseMatrix[1][0]) % 26;
product[0][1] = (keyMatrix[0][0] * reverseMatrix[0][1] + keyMatrix[0][1] * reverseMatrix[1][1]) % 26;
product[1][0] = (keyMatrix[1][0] * reverseMatrix[0][0] + keyMatrix[1][1] * reverseMatrix[1][0]) % 26;
product[1][1] = (keyMatrix[1][0] * reverseMatrix[0][1] + keyMatrix[1][1] * reverseMatrix[1][1]) % 26;

// Check if product is the identity matrix (1,0,0,1)


if (product[0][0] != 1 || product[0][1] != 0 || product[1][0] != 0 || product[1][1] != 1) {
throw new java.lang.Error("Invalid reverse matrix found!");
}
}

// Method to calculate the reverse key matrix


private static int[][] reverseMatrix(int[][] keyMatrix) {
int detmod26 = (keyMatrix[0][0] * keyMatrix[1][1] - keyMatrix[0][1] * keyMatrix[1][0]) % 26;
int factor;
int[][] reverseMatrix = new int[2][2];

// Find the factor for which factor * det = 1 mod 26


for (factor = 1; factor < 26; factor++) {
if ((detmod26 * factor) % 26 == 1) {
break;
}
}

// Calculate the reverse key matrix elements using the factor found
reverseMatrix[0][0] = keyMatrix[1][1] * factor % 26;
reverseMatrix[0][1] = (26 - keyMatrix[0][1]) * factor % 26;
reverseMatrix[1][0] = (26 - keyMatrix[1][0]) * factor % 26;
reverseMatrix[1][1] = keyMatrix[0][0] * factor % 26;

return reverseMatrix;
}

// Method to print the result of encryption/decryption

private static void echoResult(String label, int adder, ArrayList<Integer> phrase) {


System.out.print(label);

20 | P a g e
210180107028 Information Security (3170720)

for (int i = 0; i < phrase.size(); i += 2) {


System.out.print(Character.toChars(phrase.get(i) + (64 + adder)));
System.out.print(Character.toChars(phrase.get(i + 1) + (64 + adder)));
if (i + 2 < phrase.size()) {
System.out.print("-");
}
}

System.out.println();
}

// Method for encryption


public static void encrypt(String phrase, boolean alphaZero) {
int adder = alphaZero ? 1 : 0;
ArrayList<Integer> phraseToNum = new ArrayList<>();
ArrayList<Integer> phraseEncoded = new ArrayList<>();

phrase = phrase.replaceAll("[^a-zA-Z]", "").toUpperCase();

// Make the phrase length even by adding "Q" if necessary


if (phrase.length() % 2 == 1) {
phrase += "Q";
}

// Get the key matrix


int[][] keyMatrix = getKeyMatrix();
isValidMatrix(keyMatrix);

// Convert characters to numbers (ASCII - 64) and adjust for adder


for (int i = 0; i < phrase.length(); i++) {
phraseToNum.add(phrase.charAt(i) - (64 + adder));
}

// Encrypt the phrase with the key matrix


for (int i = 0; i < phraseToNum.size(); i += 2) {
int x = (keyMatrix[0][0] * phraseToNum.get(i) + keyMatrix[0][1] * phraseToNum.get(i + 1)) % 26;
int y = (keyMatrix[1][0] * phraseToNum.get(i) + keyMatrix[1][1] * phraseToNum.get(i + 1)) % 26;
phraseEncoded.add(alphaZero ? x : (x == 0 ? 26 : x));
phraseEncoded.add(alphaZero ? y : (y == 0 ? 26 : y));
}

// Print the encrypted result


echoResult("Encoded phrase: ", adder, phraseEncoded);
}

// Method for decryption


public static void decrypt(String phrase, boolean alphaZero) {
int adder = alphaZero ? 1 : 0;
ArrayList<Integer> phraseToNum = new ArrayList<>();
ArrayList<Integer> phraseDecoded = new ArrayList<>();

phrase = phrase.replaceAll("[^a-zA-Z]", "").toUpperCase();

// Get the key matrix


int[][] keyMatrix = getKeyMatrix();

isValidMatrix(keyMatrix);

// Convert characters to numbers (ASCII - 64) and adjust for adder


for (int i = 0; i < phrase.length(); i++) {

21 | P a g e
210180107028 Information Security (3170720)
phraseToNum.add(phrase.charAt(i) - (64 + adder));
}

// Get the reverse key matrix


int[][] revKeyMatrix = reverseMatrix(keyMatrix);
isValidReverseMatrix(keyMatrix, revKeyMatrix);

// Decrypt the phrase with the reverse key matrix


for (int i = 0; i < phraseToNum.size(); i += 2) {
phraseDecoded.add((revKeyMatrix[0][0] * phraseToNum.get(i) + revKeyMatrix[0][1] * phraseToNum.get(i +
1)) % 26);
phraseDecoded.add((revKeyMatrix[1][0] * phraseToNum.get(i) + revKeyMatrix[1][1] * phraseToNum.get(i +
1)) % 26);
}

// Print the decrypted result


echoResult("Decoded phrase: ", adder, phraseDecoded);
}

// Main method
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String opt, phrase;

System.out.println("Hill Cipher Implementation (2x2)");


System.out.println("-------------------------");
System.out.println("1. Encrypt text (A=0,B=1,...Z=25)");
System.out.println("2. Decrypt text (A=0,B=1,...Z=25)");
System.out.println("3. Encrypt text (A=1,B=2,...Z=26)");
System.out.println("4. Decrypt text (A=1,B=2,...Z=26)");
System.out.println("Type any other character to exit");
System.out.print("Select your choice: ");
opt = sc.nextLine();

switch (opt) {
case "1":
System.out.print("Enter phrase to encrypt: ");
phrase = sc.nextLine();
encrypt(phrase, true);
break;
case "2":
System.out.print("Enter phrase to decrypt: ");
phrase = sc.nextLine();
decrypt(phrase, true);
break;
case "3":

System.out.print("Enter phrase to encrypt: ");


phrase = sc.nextLine();
encrypt(phrase, false);
break;
case "4":
System.out.print("Enter phrase to decrypt: ");
phrase = sc.nextLine();
decrypt(phrase, false);
break;
}
}
}

22 | P a g e
210180107028 Information Security (3170720)

Output:
Hill Cipher Implementation (2x2)
-------------------------
1. Encrypt text (A=0,B=1,...Z=25)
2. Decrypt text (A=0,B=1,...Z=25)
3. Encrypt text (A=1,B=2,...Z=26)
4. Decrypt text (A=1,B=2,...Z=26)
Type any other character to exit
Select your choice: 2
Enter phrase to decrypt: kill
Enter key matrix:
vedd
Decoded phrase: CS-LK

Conclusion:

By Performing Experiment 3, We understand the working fundamental of Hill Cipher to carry out
Implementation of Hill cipher encryption-decryption.

Quiz:

1. What preliminary knowledge required for Hill cipher ?

 To understand the Hill cipher, We should have an elementary knowledge of matrices. The Hill
cipher is a type of block cipher that uses matrix multiplication to encrypt plaintext into
ciphertext.

2. Hill cipher is example of which type of cipher technique?

 The Hill cipher is a polygraphic substitution cipher and a block cipher that uses linear algebra
and matrix multiplication to encrypt and decrypt text.

Suggested Reference:
1. https://crypto.interactive-maths.com/hill-cipher.html

References used by the students:


1. https://crypto.interactive-maths.com/hill-cipher.htm

Rubric wise marks obtained:

Rubrics 1 2 3 4 5 Total
Marks

23 | P a g e
210180107028 Information Security (3170720)

Experiment No: 4
Implementation of Vigenere cipher
Date:
Relevant CO: Explore the basic principles of the symmetric cryptography and techniques with their
strengths and weaknesses from perspective of cryptanalysis

Objectives: (a) to understand working fundamental of Vigenere Cipher


(b) to carry out Implementation of Vigenere cipher encryption-decryption.

Equipment/Instruments: Computer System, Turbo-c/ JDK


Theory:
To encrypt, a table of alphabets can be used, termed a tabula recta, Vigenère square, or Vigenère
table. It consists f the alphabet written out 26 times in differ nt rows, each alphabet shifted cyclically
to the left compared to the previous alphabet, corresponding to the 26 possible Caesar ciphers. At
different points in the encryption process, the cipher uses a different alphabet from one of the rows.
The alphabet used at each point repeating keyword depends on a Each row starts with a key letter.
The remainder of the row holds the letters A to Z. Although there are 26 key rows shown, you will
only use as many keys as there are unique letters in the key string, here just 5 keys, {L, E, M, O, N}.
For successive letters of the message, we are going to take successive letters of the key string, and
encipher each message letter using its corresponding key row. Choose the next letter of the key, go al
ng that row to find the column heading that atches the message character; the letter at the
intersection of [key-row, msg-col] is the enciphered letter.

Example:

24 | P a g e
210180107028 Information Security (3170720)

Algorithm:

STEP-1: Arrange the alphabets in row and column of a 26*26 matrix.


STEP-2: Circulate the alphabets in each row to position left such that the first letter is
attached to last.
STEP-3: Repeat this process for all 26 rows and construct the final key matrix.
STEP-4: The keyword and the plain text is read from the user.
STEP-5: The characters in the keyword are repeated sequentially so as to match with
that of the plain text.
STEP-6: Pick the first letter of the plain text and that of the keyword as the row indices
and column indices respectively.
STEP-7: The junction character where these two meet forms the cipher character.
STEP-8: Repeat the above steps to generate the entire cipher text.

Program:

package VengenceCipher;

import java.util.*;

//Main class
public class VigenereCipher {
@SuppressWarnings("resource")
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the plaintext: ");
String pt = sc.nextLine().toUpperCase();
System.out.print("Enter the keyword: ");
String keyword = sc.nextLine().toUpperCase();

String encryptedText = encrypt(pt, keyword);


String decryptedText = decrypt(encryptedText, keyword);

System.out.println("\nEncrypted Text: " + encryptedText);


System.out.println("Decrypted Text: " + decryptedText);
}

// Method for encryption


private static String encrypt(String plaintext, String keyword) {
StringBuilder cipher = new StringBuilder();

for (int i = 0, j = 0; i < plaintext.length(); i++) {


char currentChar = plaintext.charAt(i);
if (Character.isAlphabetic(currentChar)) {
// Calculate shift for the current letter
int shift = keyword.charAt(j % keyword.length()) - 'A';
// Apply the shift and append to the ciphertext
char encryptedChar = (char) ((currentChar + shift - 'A') % 26 + 'A');
cipher.append(encryptedChar);

// Move to the next letter in the keyword


j++;

25 | P a g e
210180107028 Information Security (3170720)
} else {
// If the character is not alphabetic, leave it unchanged
cipher.append(currentChar);
}
}
return cipher.toString();
}

// Method for decryption


private static String decrypt(String ciphertext, String keyword) {
StringBuilder decryptedText = new StringBuilder();

for (int i = 0, j = 0; i < ciphertext.length(); i++) {


char currentChar = ciphertext.charAt(i);
if (Character.isAlphabetic(currentChar)) {
// Calculate shift for the current letter
int shift = keyword.charAt(j % keyword.length()) - 'A';
// Apply the reverse shift and append to the decrypted text
char decryptedChar = (char) ((currentChar - shift - 'A' + 26) % 26 + 'A');
decryptedText.append(decryptedChar);
// Move to the next letter in the keyword
j++;
} else {
// If the character is not alphabetic, leave it unchanged
decryptedText.append(currentChar);
}
}
return decryptedText.toString();
}
}

Output:
Enter the plaintext: hello world
Enter the keyword: 1234

Encrypted Text: 86>?? HAE<5


Decrypted Text: 86>?? XPS<5

Conclusion:

By Performing Experiment 4, We understand the working fundamental of Vigenere Cipher to carry


out Implementation of Vigenere cipher encryption-decryption.

Quiz:

1. Encryption in Vigenere cipher is done using _____________

 A Vigenère square or table and a polyalphabetic substitution method.

Suggested Reference:
1. https://intellipaat.com/blog/vigenere-cipher/

26 | P a g e
210180107028 Information Security (3170720)

References used by the students:

1. https://intellipaat.com/blog/vigenere-cipher/

Rubric wise marks obtained:

Rubrics 1 2 3 4 5 Total
Marks

27 | P a g e
210180107028 Information Security (3170720)

Experiment No: 5
Implementation of Rail Fence Transposition
Date:
Relevant CO: Explore the basic principles of the symmetric cryptography and techniques with their
strengths and weaknesses from perspective of cryptanalysis

Objectives: (a) to understand working fundamental of Rail Fence Transposition Cipher


(b) to carry out Implementation of Rail Fence Transposition Cipher encryption-
decryption.

Equipment/Instruments: Computer System, Turbo-c/ JDK


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

Example:

Algorithm:

STEP-1: Read the Plain text.


STEP-2: Arrange the plain text in row columnar matrix format.
STEP-3: Now read the keyword depending on the number of columns of the plain text.
STEP-4: Arrange the characters of the keyword in sorted order and the corresponding
columns of the plain text.

STEP-5: Read the characters row wise or column wise in the former order to get thecipher
text.

28 | P a g e
210180107028 Information Security (3170720)
Program:

package RailFance;

import java.util.Arrays;

public class RailFence {

// Function to encrypt a message using Rail Fence Cipher


public static String encryptRailFence(String text, int key) {
// Create the matrix to cipher plain text
// key = rows, length(text) = columns
char[][] rail = new char[key][text.length()];

// Fill the rail matrix to distinguish filled spaces from blank ones
for (int i = 0; i < key; i++)
Arrays.fill(rail[i], '\n');

// To determine the direction of movement


boolean dirDown = false;
int row = 0, col = 0;

// Loop through the text to fill the rail matrix


for (int i = 0; i < text.length(); i++) {
// Reverse the direction if we have reached the top or bottom rail
if (row == 0 || row == key - 1)
dirDown = !dirDown;

// Place the character in the matrix


rail[row][col++] = text.charAt(i);

// Move to the next row based on the direction


row = dirDown ? row + 1 : row - 1;
}

// Construct the encrypted message by reading characters row by row


StringBuilder result = new StringBuilder();
for (int i = 0; i < key; i++) {
for (int j = 0; j < text.length(); j++) {
if (rail[i][j] != '\n') {
result.append(rail[i][j]);
}
}
}

return result.toString();
}

// Function to decrypt a message using Rail Fence Cipher


public static String decryptRailFence(String cipher, int key) {
// Create the matrix to cipher plain text
// key = rows, length(cipher) = columns
char[][] rail = new char[key][cipher.length()];

// Fill the rail matrix to distinguish filled spaces from blank ones
for (int i = 0; i < key; i++)
Arrays.fill(rail[i], '\n');

// To find the direction of flow


boolean dirDown = true;
int row = 0, col = 0;

// Mark the positions in the matrix where characters will be placed


for (int i = 0; i < cipher.length(); i++) {

29 | P a g e
210180107028 Information Security (3170720)
if (row == 0)
dirDown = true;
if (row == key - 1)
dirDown = false;

// Place the marker


rail[row][col++] = '*';

// Find the next row using the direction flag


row = dirDown ? row + 1 : row - 1;
}

// Fill the rail matrix with characters from the ciphertext


int index = 0;
for (int i = 0; i < key; i++) {
for (int j = 0; j < cipher.length(); j++) {
if (rail[i][j] == '*' && index < cipher.length()) {
rail[i][j] = cipher.charAt(index++);
}
}
}

// Construct the decrypted message by traversing the matrix


StringBuilder result = new StringBuilder();
row = 0;
col = 0;
dirDown = true;

for (int i = 0; i < cipher.length(); i++) {


if (row == 0)
dirDown = true;
if (row == key - 1)
dirDown = false;

if (rail[row][col] != '*') {
result.append(rail[row][col++]);
}

// Find the next row using the direction flag


row = dirDown ? row + 1 : row - 1;
}

return result.toString();
}

// Main method to test the Rail Fence cipher


public static void main(String[] args) {
// Encryption
System.out.println("Encrypted Message: ");
System.out.println(encryptRailFence("attack at once", 2));
System.out.println(encryptRailFence("GeeksforGeeks ", 3));
System.out.println(encryptRailFence("defend the east wall", 3));

// Decryption of the cipher text

System.out.println("\nDecrypted Message: ");


System.out.println(decryptRailFence("atc toctaka ne", 2));

30 | P a g e
210180107028 Information Security (3170720)
System.out.println(decryptRailFence("GsGsekfrek eoe", 3));
System.out.println(decryptRailFence("dnhaweedtees alf tl", 3));
}
}

Output:
Encrypted Message:
atc toctaka ne
GsGsekfrek eoe
dnhaweedtees alf tl

Decrypted Message:
attack at once
GeeksforGeeks
defend the east wall

Conclusion:

By Performing Experiment 5, We understand the working fundamental of Railfence cipher to carry


out Implementation of Railfence cipher encryption-decryption.

Quiz:

1. Encryption in Rail fence cipher is done using _____________


a) by arranging the letters in a zig zag fashion in a table
b) by randomly arranging letters
c) by arranging letters in vigenere table
d) by swapping adjacent letters
 b.

2. Rail fence cipher is more secure than one time pad cipher? True/False
 False Statement, the one-time pad cipher is more secure than the rail fence cipher.

Suggested Reference:
1. https://crypto.interactive-maths.com/rail-fence-cipher.html

References used by the students:


1. https://crypto.interactive-maths.com/rail-fence-cipher.html

Rubric wise marks obtained:

Rubrics 1 2 3 4 5 Total
Marks

31 | P a g e
210180107028 Information Security (3170720)

Experiment No: 6
Implementation of Simple DES
Date:
Relevant CO: Implement and analyze various symmetric key cryptography algorithms
and their application in different context

Objectives: (a) to understand working fundamental of DES Algorithm


(b) to carry out Implementation of DES encryption-decryption.

Equipment/Instruments: Computer System, Turbo-c/ JDK


Theory:
DES is a symmetric encryption system that uses 64-bit blocks, 8 bits of which are
used for parity checks. The key therefore has a "useful" length of 56 bits, which means that
only 56 bits are actually used in the algorithm. The algorithm involves carrying out
combinations, substitutions and permutations between the text to be encrypted and the key,
while making sure the operations can be performed in both directions. The key is ciphered on
64 bits and made of 16 blocks of 4 bits, generally denoted k1 to k16. Given that "only" 56 bits
are actually used for encrypting, there can be 256 different keys.

The main parts of the algorithm are as follows:


➢ Fractioning of the text into 64-bit blocks
➢ Initial permutation of blocks
➢ Breakdown of the blocks into two parts: left and right, named L and R
➢ Permutation and substitution steps repeated 16 times
➢ Re-joining of the left and right parts then inverse initial permutation.

32 | P a g e
210180107028 Information Security (3170720)
Example:

Algorithm:

STEP-1: Read the 64-bit plain text.


STEP-2: Split it into two 32-bit blocks and store it in two different arrays.
STEP-3: Perform XOR operation between these two arrays.
STEP-4: The output obtained is stored as the second 32-bit sequence and the original
second 32-bit sequence forms the first part.

STEP-5: Thus the encrypted 64-bit cipher text is obtained in this way. Repeat the same
process for the remaining plain text characters.

Program:

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Scanner;

public class SimpleDES {

// Method to encrypt a string using DES


public static String encrypt(String plainText, SecretKey secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}

33 | P a g e
210180107028 Information Security (3170720)

// Method to decrypt an encrypted string using DES


public static String decrypt(String encryptedText, SecretKey secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
return new String(decryptedBytes);
}

public static void main(String[] args) throws Exception {


Scanner sc = new Scanner(System.in);

// Get input from the user


System.out.print("Enter text to be encrypted: ");
String plainText = sc.nextLine();

// Generate a DES key


KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
SecretKey secretKey = keyGenerator.generateKey();

// Encrypt the user input


String encryptedText = encrypt(plainText, secretKey);
System.out.println("Encrypted Text: " + encryptedText);

// Decrypt the encrypted text


String decryptedText = decrypt(encryptedText, secretKey);
System.out.println("Decrypted Text: " + decryptedText);
}
}

Output:
Enter text to be encrypted: hello world
Encrypted Text: UNqgO83wnG5fHASFcyV8Sw==
Decrypted Text: hello world

Conclusion:

By Performing Experiment 6, We understand the working fundamental of Des Algorithm to carry


out Implementation of DES.

Quiz:

1. DES works on _______ size of blocks ?

 The Data Encryption Standard (DES) works on blocks of 64 bits in size.

2. How many steps DES consists?

 16 Rounds.

34 | P a g e
210180107028 Information Security (3170720)

Suggested Reference:
1. https://www.tutorialspoint.com/cryptography/data_encryption_standard.html

References used by the students:


1. https://www.tutorialspoint.com/cryptography/data_encryption_standard.html

Rubric wise marks obtained:

Rubrics 1 2 3 4 5 Total
Marks

35 | P a g e
210180107028 Information Security (3170720)

Experiment No: 7
Implementation of AES
Date:
Relevant CO: Implement and analyze various symmetric key cryptography algorithms
and their application in different context

Objectives: (a) to understand working fundamental of AES Algorithm


(b) to carry out Implementation of AES encryption-decryption.

Equipment/Instruments: Computer System, Turbo-c/ JDK


Theory:
AES is a symmetric encryption system that uses 128 bit blocks, The key length is
128/192/256. The algorithm involves carrying out combinations, substitutions and
permutations between the text to be encrypted and the key, while making sure the operations
can be performed in both directions.
The main parts of the algorithm are as follows:
 AES is a block cipher.
 The key size can be 128/192/256 bits.
 Encrypts data in blocks of 128 bits each
.

Example:

Algorithm:

STEP-1:Derive the set of round keys from the cipher key.

36 | P a g e
210180107028 Information Security (3170720)
STEP-2:Initialize the state array with the block data (plaintext).
STEP-3:Add the initial round key to the starting state array.
STEP-4:Perform nine rounds of state manipulation.
STEP-5:Perform the tenth and final round of state manipulation.
STEP-6:Copy the final state array out as the encrypted data (ciphertext).

Program:

package AesExample;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.util.Base64;
import java.util.Scanner;

public class AesExample {

// Method to encrypt a string using DES


public static String encrypt(String plainText, SecretKey secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}

// Method to decrypt an encrypted string using DES


public static String decrypt(String encryptedText, SecretKey secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
return new String(decryptedBytes);
}

@SuppressWarnings("resource")
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);

// Prompt the user for the plaintext input


System.out.print("Enter the text to be encrypted: ");
String plainText = sc.nextLine();

// Generate a DES key


KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
SecretKey secretKey = keyGenerator.generateKey();

// Encrypt the user input


String encryptedText = encrypt(plainText, secretKey);
System.out.println("Encrypted Text: " + encryptedText);

// Ask the user if they want to decrypt the encrypted text


System.out.print("Do you want to decrypt the text? (yes/no): ");
String response = sc.nextLine();

if (response.equalsIgnoreCase("yes")) {
// Decrypt the encrypted text
String decryptedText = decrypt(encryptedText, secretKey);
System.out.println("Decrypted Text: " + decryptedText);
} else {
37 | P a g e
210180107028 Information Security (3170720)
System.out.println("Exiting without decryption.");
}
}
}

Output:
Enter the text to be encrypted: hello sir
Encrypted Text: cwnPTay2l5ssYARI6wyjTg==
Do you want to decrypt the text? (yes/no): yes
Decrypted Text: hello sir

Conclusion:

By Performing Experiment 7, We understand the working fundamental of AES Algorithm to carry


out Implementation of AES.

Quiz:

1. How many rounds does the AES-192 perform ?

 12 Rounds.

Suggested Reference:
1. https://www.geeksforgeeks.org/advanced-encryption-standard-aes/

References used by the students:

Rubric wise marks obtained:

Rubrics 1 2 3 4 5 Total
Marks

38 | P a g e
210180107028 Information Security (3170720)

Experiment No: 8
Implementation of RSA Algorithm
Date:
Relevant CO: Compare public key cryptography with private key cryptography and
Implement various asymmetric key cryptography algorithms

Objectives: (a) to understand working fundamental of RSA Algorithm


(b) to carry out Implementation of RSA encryption-decryption.

Equipment/Instruments: Computer System, Turbo-c/ JDK


Theory:
RSA is an algorithm used by modern computers to encrypt and decrypt messages. It
is an asymmetric cryptographic algorithm. Asymmetric means that there are two different
keys. This is also called public key cryptography, because one of them can be given to
everyone. A basic principle behind RSA is the observation that it is practical to find three
very large positive integers e, d and n such that with modular exponentiation for all
integer m:

(me)d = m (mod n)

The public key is represented by the integers n and e; and, the private key, by the integer d. m
represents the message. RSA involves a public key and a private key. The public key can be known
by everyone and is used for encrypting messages. The intention is that messages encrypted with the
public key can only be decrypted in a reasonable amount of time using the private key.

Example:

39 | P a g e
210180107028 Information Security (3170720)

Algorithm:

STEP-1: Select two co-prime numbers as p and q.


STEP-2: Compute n as the product of p and q.
STEP-3: Compute (p-1)*(q-1) and store it in z.
STEP-4: Select a random prime number e that is less than that of z.
STEP-5: Compute the private key, d as e * mod-1(z).
STEP-6: The cipher text is computed as messagee * mod n.STEP-7: Decryption is done as
cipherdmod n.

Program:

package RsaExample;

import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Scanner;

public class RsaExample {

private BigInteger n, d, e;
private int bitlen = 1024; // Bit length for key generation

// Constructor to generate the keys


public RsaExample() {
SecureRandom random = new SecureRandom();
BigInteger p = BigInteger.probablePrime(bitlen / 2, random);
BigInteger q = BigInteger.probablePrime(bitlen / 2, random);
n = p.multiply(q);
BigInteger phi = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE));
e = BigInteger.probablePrime(bitlen / 2, random);
while (phi.gcd(e).compareTo(BigInteger.ONE) > 0 && e.compareTo(phi) < 0) {
e.add(BigInteger.ONE);
}
d = e.modInverse(phi);
}

// Encryption method
public BigInteger encrypt(BigInteger message) {
return message.modPow(e, n);
}

// Decryption method
public BigInteger decrypt(BigInteger encryptedMessage) {
return encryptedMessage.modPow(d, n);
}

// Main method to run the program


public static void main(String[] args) {
RsaExample rsa = new RsaExample();
Scanner sc = new Scanner(System.in);

// Prompt user for the message to encrypt


System.out.print("Enter the message (as a string) to encrypt: ");
String message = sc.nextLine();

// Convert the message to a BigInteger


40 | P a g e
210180107028 Information Security (3170720)
BigInteger messageToEncrypt = new BigInteger(message.getBytes());

// Encrypt the message


BigInteger encryptedMessage = rsa.encrypt(messageToEncrypt);
System.out.println("Encrypted Message: " + encryptedMessage);

// Ask the user if they want to decrypt the message


System.out.print("Do you want to decrypt the message? (yes/no): ");
String response = sc.nextLine();

if (response.equalsIgnoreCase("yes")) {
// Decrypt the message
BigInteger decryptedMessage = rsa.decrypt(encryptedMessage);
String decryptedText = new String(decryptedMessage.toByteArray());
System.out.println("Decrypted Message: " + decryptedText);
} else {
System.out.println("Exiting without decryption.");
}

sc.close();
}
}

Output:
Enter the message (as a string) to encrypt: Hii dude
Encrypted Message:
8287552099262694309095305037918313455492694638364970321921861296902473672937319132917725
1950356172115195482651233522134341751502823808410152668206552891983095650528585596916107
4137485479033714421944020939645757053958651448644599496626859096078674831660175303467643
89595541518246393265192951701361337297867915
Do you want to decrypt the message? (yes/no): yes
Decrypted Message: Hii dude

Conclusion:

By Performing Experiment 8, We understand the working fundamental of RSA Algorithm to carry


out Implementation of RSA.

Quiz:

1. if p=7, q=1 and e=13 than what will be value of d ?


 0.

Suggested Reference:
1. https://www.cemc.uwaterloo.ca/resources/real-world/RSA.pdf

References used by the students:

1. https://www.cemc.uwaterloo.ca/resources/real-world/RSA.pdf

41 | P a g e
210180107028 Information Security (3170720)

Rubric wise marks obtained:

Rubrics 1 2 3 4 5 Total
Marks

42 | P a g e
210180107028 Information Security (3170720)

Experiment No: 9
Implementation of Diffie–Hellman Key Exchange
Date:
Relevant CO: Compare public key cryptography with private key cryptography and
Implement various asymmetric key cryptography algorithms

Objectives: (a) to understand working fundamental of Diffie–Hellman Key Exchange


(b) to carry out Implementation of Diffie–Hellman Key Exchange algorithm.

Equipment/Instruments: Computer System, Turbo-c/ JDK


Theory:
Diffie–Hellman Key Exchange establishes a shared secret between two parties that can be used for
secret communication for exchanging data over a public network. It is primarily used as a method
of exchanging cryptography keys for use in symmetric encryption algorithms like AES. The
algorithm in itself is very simple. The process begins by having the two parties, Alice and Bob. Let's
assume that Alice wants to establish a shared secret with Bob.

Example:

Algorithm:

STEP-1: Both Alice and Bob shares the same public keys g and p.
STEP-2: Alice selects a random public key a.
STEP-3: Alice computes his secret key A as ga mod p.
STEP-4: Then Alice sends A to Bob.
STEP-5: Similarly Bob also selects a public key b and computes his secret key as Band
sends the same back to Alice.

43 | P a g e
210180107028 Information Security (3170720)
STEP-6: Now both of them compute their common secret key as the other one’s secretkey
power of a mod p.

Program:

package DeffiHellman;

import java.math.BigInteger;
import java.util.Scanner;

public class DeffiHellman {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

// Publicly known values (p is a prime number, g is a primitive root modulo p)


System.out.print("Enter a prime number (p): ");
BigInteger p = sc.nextBigInteger();

System.out.print("Enter a primitive root modulo p (g): ");


BigInteger g = sc.nextBigInteger();

// Alice's private key (a)


System.out.print("Enter Gaurav's private key (a): ");
BigInteger a = sc.nextBigInteger();

// Bob's private key (b)


System.out.print("Enter sir's private key (b): ");
BigInteger b = sc.nextBigInteger();

// Calculate Alice's public key: A = g^a mod p


BigInteger A = g.modPow(a, p);
System.out.println("Gaurav's public key (A): " + A);

// Calculate Bob's public key: B = g^b mod p


BigInteger B = g.modPow(b, p);
System.out.println("Sir's public key (B): " + B);

// Alice calculates the shared secret: S = B^a mod p


BigInteger aliceSharedSecret = B.modPow(a, p);
System.out.println("Gaurav's shared secret (S): " + aliceSharedSecret);

// Bob calculates the shared secret: S = A^b mod p


BigInteger bobSharedSecret = A.modPow(b, p);
System.out.println("sir's shared secret (S): " + bobSharedSecret);

// Verify if both shared secrets are the same


if (aliceSharedSecret.equals(bobSharedSecret)) {
System.out.println("Shared secret successfully established!");
} else {
System.out.println("Error in calculating shared secret!");
}

sc.close();
}
}

Output:
44 | P a g e
210180107028 Information Security (3170720)

Enter a prime number (p): 59


Enter a primitive root modulo p (g): 26
Enter Gaurav's private key (a): 200
Enter sir's private key (b): 10
Gaurav's public key (A): 49
Sir's public key (B): 48
Gaurav's shared secret (S): 25
sir's shared secret (S): 25
Shared secret successfully established!

Conclusion:

By Performing Experiment 9, We understand the working fundamental of Deffi-Hellman Algorithm


to carry out Implementation of Deffi-Hellman.

Quiz:

1. Suppose that two parties A and B wish to set up a common secret key (D-H key) between
themselves using the Diffie Hellman key exchange technique. They agree on 7 as the modulus
and 3 as the primitive root. Party A chooses 2 and party B chooses 5 as their respective secrets.
Their D-H key is ?

 Party A’s Secret key Will be 4 & Party B’s Secrect Key Will b.

Suggested Reference:
1. https://www.techtarget.com/searchsecurity/definition/Diffie-Hellman-key-exchange

References used by the students:

1. https://www.techtarget.com/searchsecurity/definition/Diffie-Hellman-key-exchange

Rubric wise marks obtained:

Rubrics 1 2 3 4 5 Total
Marks

45 | P a g e
210180107028 Information Security (3170720)

Experiment No: 10
Implementation of MD-5
Date:
Relevant CO: Explore the concept of hashing and implement various hashing
algorithms for message integrity

Objectives: (a) to understand working fundamental of MD5


(b) to carry out Implementation of MD5 techniques.

Equipment/Instruments: Computer System, Turbo


Turbo-c/ JDK
Theory:
MD5 processes a varia ble-length message into a fixed-length output of 128 bits. The
input message is broken up into chunks of 512-bit blocks. The message is pa dded so that its
e
length is divisible by 512. The padding works as follows: first a single bit, 1, is appended to
the end of the message. This is followed by as many zeros as are required to bring the length
of the message up to 64 bits less than a multiple of 512. The remaining bits are filled up with
64 bits representing the length of the original message, modulo 264.The main operates on a
128-bit state, divided into four 32-bit words, denoted A, B, C, and D. These are initialized to
certain fixed constants. The main algorithm then uses each 512-bit message block in turn
to modify the stat ..

Example:

46 | P a g e
210180107028 Information Security (3170720)
Algorithm:

STEP-1: Read the 128-bit plain text.


STEP-2: Divide into four blocks of 32-bits named as A, B, C and D.

STEP-3: Compute the functions f, g, h and i with operations such as, rotations,
permutations, etc,.
STEP-4: The output of these functions are combined together as F and performed
circular shifting and then given to key round.

STEP-5: Finally, right shift of ‘s’ times are performed and the results are combinedtogether to
produce the final output.

Program:

package MD5;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Scanner;

public class MD5 {

public static String getMD5Hash(String input) {


try {
// Create an instance of the MD5 digest
MessageDigest md = MessageDigest.getInstance("MD5");

// Digest the input string and return the hash as a byte array
byte[] messageDigest = md.digest(input.getBytes());

// Convert byte array to hex format


StringBuilder hexString = new StringBuilder();
for (byte b : messageDigest) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();

} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}

@SuppressWarnings("resource")
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

// Prompt the user to enter a string


System.out.println("Enter the string to hash using MD5: ");
String input = sc.nextLine();

// Get the MD5 hash of the input string


String hash = getMD5Hash(input);

47 | P a g e
210180107028 Information Security (3170720)
// Output the MD5 hash
System.out.println("MD5 Hash of the input: " + hash);
}
}

Output:
Enter the string to hash using MD5:
Hello
MD5 Hash of the input: 8b1a9953c4611296a827abf8c47804d7

Conclusion:

By Performing Experiment 10, We understand the working fundamental of MD-5 Hashing


Algorithm to carry out Implementation of MD-5.

Quiz:

1. MD5 produce hash value of ____ bits ?

 The MD5 algorithm is a cryptographic hash function that produces a 128-bit (16-byte) hash value
from any given input.

Suggested Reference:
1. https://www.simplilearn.com/tutorials/cyber-security-tutorial/md5-algorithm

References used by the students:


1. https://www.simplilearn.com/tutorials/cyber-security-tutorial/md5-algorithm

Rubric wise marks obtained:

Rubrics 1 2 3 4 5 Total
Marks

48 | P a g e
210180107028 Information Security (3170720)

Experiment No: 11
Implementation of SHA-1
Date:
Relevant CO: Explore the concept of hashing and implement various hashing
algorithms for message integrity

Objectives: (a) to understand working fundamental of SHA-1


(b) to carry out Implementation of SHA-1.

Equipment/Instruments: Computer System, Turbo-c/ JDK


Theory:
In cryptography, SHA-1 (Secure Hash Algorithm 1) is a cryptographic hash function. SHA-1
produces a 160-bit hash value known as a message digest. The waythis algorithm
works is that for a message of size < 264 bits it computes a 160-bit condensed output called a
message digest. The SHA-1 algorithm is designed so that it is practically infeasible to find two input
messages that hash to the same output message. A hash function such as SHA-1 is used to calculate
an alphanumeric string that serves as the cryptographic representation of a file or a piece of data.
This is called a digest and can serve as a digital signature. It is supposed to be unique and non-
reversible.

Example:

Algorithm:

STEP-1: Read the 256-bit key values.


STEP-2: Divide into five equal-sized blocks named A, B, C, D and E.
STEP-3: The blocks B, C and D are passed to the function F.
STEP-4: The resultant value is permuted with block E.

49 | P a g e
210180107028 Information Security (3170720)
STEP-5: The block A is shifted right by ‘s’ times and permuted with the result of step-4.

STEP-6: Then it is permuted with a weight value and then with some other key pair and
taken as the first block.
STEP-7: Block A is taken as the second block and the block B is shifted by ‘s’ times and
taken as the third block.

STEP-8: The blocks C and D are taken as the block D and E for the final output.

Program:

package SHA1;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Scanner;

public class SHA1 {

public static String getSHA1Hash(String input) {


try {
// Create an instance of the SHA-1 digest
MessageDigest md = MessageDigest.getInstance("SHA-1");

// Digest the input string and return the hash as a byte array
byte[] messageDigest = md.digest(input.getBytes());

// Convert byte array to hex format


StringBuilder hexString = new StringBuilder();
for (byte b : messageDigest) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();

} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}

@SuppressWarnings("resource")
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

// Prompt the user to enter a string


System.out.println("Enter the string to hash using SHA-1: ");
String input = sc.nextLine();

// Get the SHA-1 hash of the input string


String hash = getSHA1Hash(input);

// Output the SHA-1 hash


System.out.println("SHA-1 Hash of the input: " + hash);

}
}

50 | P a g e
210180107028 Information Security (3170720)

Output:

Enter the string to hash using SHA-1:


hey
SHA-1 Hash of the input: 7f550a9f4c44173a37664d938f1355f0f92a47a7

Conclusion:

By Performing Experiment 11, We understand the working fundamental of SHA-1 Hashing


Algorithm to carry out Implementation of SHA-1.

Quiz:

1. What is the number of round computation steps in the SHA-256 algorithm ?


 64 rounds

2. SHA-1 produces a hash value of _____ bits ?


 160-bit

Suggested Reference:
1. https://www.geeksforgeeks.org/sha-1-hash-in-java/.

References used by the students:


1. https://www.geeksforgeeks.org/sha-1-hash-in-java/.

Rubric wise marks obtained:

Rubrics 1 2 3 4 5 Total
Marks

51 | P a g e
210180107028 Information Security (3170720)

Experiment No: 12
Implementation of digital signature standard
Date:
Relevant CO: Explore and use the techniques and standards of digital signature, key
management and authentication

Objectives: (a) to understand working fundamental of digital signature standard


(b) to carry out Implementation of digital signature standard.

Equipment/Instruments: Computer System, Turbo-c/ JDK


Theory:
Digital Signature Standard (DSS) is a Federal Information Processing Standard(FIPS) which defines
algorithms that are used to generate digital signatures with the help of Secure Hash Algorithm(SHA)
for the authentication of electronic documents. DSS only provides us with the digital signature
function and not with any encryption or key exchanging stretegy.

Example:

Algorithm:

STEP-1: Key Generation.


STEP-2: Signature Generation.
STEP-3: Key Distribution.
STEP-4: Signature Verification.

52 | P a g e
210180107028 Information Security (3170720)
Program:

package DSS;

import java.security.*;
import java.util.Base64;

public class DSS {

public static void main(String[] args) {


try {
// Generate Key Pair (Public and Private Key)

KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");


keyGen.initialize(2048); // Key size, can be 1024, 2048, or 3072 bits
KeyPair keyPair = keyGen.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();

// Original message to be signed


String message = "This is a simple example of a digital signature.";

// Create a Signature object and initialize it with the private key


Signature signature = Signature.getInstance("SHA256withDSA");
signature.initSign(privateKey);

// Sign the message


signature.update(message.getBytes());
byte[] digitalSignature = signature.sign();

// Print out the signature in base64 encoding


String signatureStr = Base64.getEncoder().encodeToString(digitalSignature);
System.out.println("Digital Signature: " + signatureStr);

// Verify the signature


signature.initVerify(publicKey);
signature.update(message.getBytes());

boolean isVerified = signature.verify(digitalSignature);


System.out.println("Signature verification: " + isVerified);

} catch (Exception e) {
e.printStackTrace();
}
}
}

Output:
Digital Signature:
MDwCHEmGR1RpI1mWUHsS6pNpj0Y1ycaeXdda+wMQu/wCHFOMmbw/Y3qv9aaHod4hmB0aZWGE481arCfc8xs=
Signature verification: true

Conclusion:

By Performing Experiment 12, We understand the working fundamental of Digital Signature


Standard to carry out Implementation of Digital Signature Standard.

53 | P a g e
210180107028 Information Security (3170720)
Quiz:

1. How many sub-algorithms digital signature consists of ?


 A digital signature scheme typically consists of three algorithms

Suggested Reference:
1. https://www.geeksforgeeks.org/digital-signature-standard-dss/

References used by the students:


https://www.geeksforgeeks.org/digital-signature-standard-dss/

Rubric wise marks obtained:

Rubrics 1 2 3 4 5 Total
Marks

54 | P a g e
210180107028 Information Security (3170720)

Experiment No: 13
Demonstrate how to work with CrypTool
Date:
Relevant CO: -----

Objectives: (a) to understand working fundamental of CrypTool

Equipment/Instruments: Computer System, CrypTool .

Introduction:

The JCrypTool installation is very simple: download and extract the zip-archive, launch the
main program and get started.

Demonstration of Caesar Encryption using CrypTool


In this CrypTool demonstration, we will use Caesar, one of the oldest encryption algorithms .

Encryption
1. Open the Cryptool UI and the document that needs to be encrypted.

2. Click Encrypt/Decrypt > Symmetric (classic) > Caesar

55 | P a g e
210180107028 Information Security (3170720)

3. Select Caesar mode and the “alphabet character” is “N.” That means that the text will have
characters replaced starting with N. So A >N, B>M, and so on. Click on “encrypt.”

4. The document is encrypted as per the configured policy. This is a very basic example of how
symmetric encryption works.

56 | P a g e
210180107028 Information Security (3170720)

Decryption process

Perform the following steps to decrypt the encrypted document.

1. Open the encrypted document, and click on “Encrypt.Decrypt” >Symmetric >Caesar.


2. Enter “N” as the alphabet character. This is the shared secret that both parties must know in
order to encrypt and decrypt.
3. Click on decrypt.

Conclusion:
57 | P a g e
210180107028 Information Security (3170720)

By Analyzing Experiment 12, We understand the working fundamental of CrypTool .

Suggested Reference:
1. https://www.c-sharpcorner.com/article/encryption-decryption-using-cryptool/

References used by the students:


1. https://www.c-sharpcorner.com/article/encryption-decryption-using-cryptool/

58 | P a g e
210180107028 Information Security (3170720)

Experiment No: 14
Demonstrate Working of Wireshark
Date:
Relevant CO:

Objectives: (a) to understand Installation/working fundamental of Wireshark

Equipment/Instruments: Computer System, Wireshark

Introduction:
The Wireshark installation is very simple: download and extract the zip-archive, launch the main
program and get started.

Installation

Installing Wireshark on Windows: Follow the below steps to install Wireshark on Windows:

Step 1: Visit the official Wireshark website using any web browser.

Step 2: Click on Download, a new webpage will open with different installers of Wireshark.

59 | P a g e
210180107028 Information Security (3170720)

Step 3: Downloading of the executable file will start shortly. It is a small 73.69 MB file that will
take some time.

Step 4: Now check for the executable file in downloads in your system and run it.

Step 5: It will prompt confirmation to make changes to your system. Click on Yes.

60 | P a g e
210180107028 Information Security (3170720)
Step 6: Setup screen will appear, click on Next.

Step 7: The next screen will be of License Agreement, click on Noted.

Step 8: This screen is for choosing components, all components are already marked so don’t change
anything just click on the Next button.

61 | P a g e
210180107028 Information Security (3170720)

Step 9: This screen is of choosing shortcuts like start menu or desktop icon along with file
extensions which can be intercepted by Wireshark, tick all boxes and click on Next button.

Step 10: The next screen will be of installing location so choose the drive which will have sufficient
memory space for installation. It needed only a memory space of 223.4 MB.

Step 11: Next screen has an option to install Npcap which is used with Wireshark to capture
packets pcap means packet capture so the install option is already checked don’t change anything
and click the next button.

62 | P a g e
210180107028 Information Security (3170720)

Step 12: Next screen is about USB network capturing so it is one’s choice to use it or not, click on
Install.

Step 13: After this installation process will start.

Step 14: This installation will prompt for Npcap installation as already checked so the license
agreement of Npcap will appear to click on the I Agree button.

63 | P a g e
210180107028 Information Security (3170720)

Step 15: Next screen is about different installing options of npcap, don’t do anything click on
Install.

Step 16: After this installation process will start which will take only a minute.

64 | P a g e
210180107028 Information Security (3170720)
Step 17: After this installation process will complete click on the Next button.

Step 18: Click on Finish after the installation process is complete.

65 | P a g e
210180107028 Information Security (3170720)

Step 19: After this installation process of Wireshark will complete click on the Next button.

Step 20: Click on Finish after the installation process of Wireshark is complete.

Wireshark is successfully installed on the system and an icon is created on the desktop as shown
below:

66 | P a g e
210180107028 Information Security (3170720)
Now run the software and see the interface.

Now you can use wireshark for packet capturing and filtering

Conclusion:

By Analyzing Experiment 14, We understand the working fundamental of CrypTool .

Suggested Reference:
1. https://www.javatpoint.com/wireshark
2. https://www.comptia.org/content/articles/what-is-wireshark-and-how-to-use-
it#:~:text=What%20Is%20Wireshark%20Used%20For,identify%20bursts%20of%20network
%20traffic.

References used by the students:


1. https://www.javatpoint.com/wireshark

67 | P a g e

You might also like