Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Is 2001 70107102

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

lOMoARcPSD|31013873

IS 2001 70107102

computer engineer (Vishwakarma University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by pranav yadav (py2180333@gmail.com)
lOMoARcPSD|31013873

A Laboratory Manual for

Information Security
(3170720)
B.E. Semester 7
(Computer

Engineering)

Enrolment No
Name
Branch
Academic Term
Institute Name

Downloaded by pranav yadav (py2180333@gmail.com)


lOMoARcPSD|31013873

Directorate of Technical Education


Gandhinagar, Gujarat

Downloaded by pranav yadav (py2180333@gmail.com)


lOMoARcPSD|31013873

Information Security (3170720) 200170107102

Vishwakarma Government Engineering College


Department: Computer Engineering

Certificate

This is to certify that Mr. Enrollment No. of B.E. Semester

7th from Computer Engineering Department of this Institute (GTU Code: 017) has

satisfactorily completed the Practical / Tutorial work for the subject Information Security

(3170720) for the academic year 2023-24.

Place:

Date:

Name and Sign of Faculty member:

Head of the Department

Downloaded by pranav yadav (py2180333@gmail.com)


lOMoARcPSD|31013873

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-based curriculum 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.

Downloaded by pranav yadav (py2180333@gmail.com)


lOMoARcPSD|31013873

DTE’s Vision

 To provide globally competitive technical education


 Remove geographical imbalances and inconsistencies
 Develop student friendly resources with a special focus on girls’ education and support to
weaker sections
 Develop programs relevant to industry and create a vibrant pool of technical professionals

Institute’s Vision

 To create an ecosystem for proliferation of socially responsible and technically sound


engineers, innovators and entrepreneurs.

Institute’s Mission

 To develop state-of-the-art laboratories and well-equipped academic infrastructure.


 To motivate faculty and staff for qualification up-gradation, and enhancement of subject
knowledge.
 To promote research, innovation and real-life problem-solving skills.
 To strengthen linkages with industries, academic and research organizations.
 To reinforce concern for sustainability, natural resource conservation and social
responsibility.

Department’s Vision

 To create an environment for providing value-based education in Computer Engineering


through innovation, team work and ethical practices.

Department’s Mission

 To produce computer engineering graduates according to the needs of industry,


government, society and scientific community.
 To develop state of the art computing facilities and academic infrastructure.
 To develop partnership with industries, government agencies and R & D organizations for
knowledge sharing and overall development of faculties and students.
 To solve industrial, governance and societal issues by applying computing techniques.
 To create environment for research and entrepreneurship.

Downloaded by pranav yadav (py2180333@gmail.com)


lOMoARcPSD|31013873

Programme Outcomes (POs)

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 analyze 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 modeling 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.

Downloaded by pranav yadav (py2180333@gmail.com)


lOMoARcPSD|31013873

3170720 INFORMATION SECURITY 200170107102

Program Specific Outcomes (PSOs)

 Sound knowledge of fundamentals of computer science and engineering including software


and hardware.
 Develop the software using sound software engineering principles having web based/mobile
based interface.
 Use various tools and technology supporting modern software frameworks for solving
problems having large volume of data in the domain of data science and machine
learning.

Program Educational Objectives (PEOs)

 Possess technical competence in solving real life problems related to Computing.


 Acquire good analysis, design, development, implementation and testing skills to formulate
simple computing solutions to the business and societal needs.
 Provide requisite skills to pursue entrepreneurship, higher studies, research, and development
and imbibe high degree of professionalism in the fields of computing.
 Embrace life-long learning and remain continuously employable.
 Work and excel in a highly competence supportive, multicultural and professional
environment which abiding to the legal and ethical responsibilities.

Downloaded by pranav yadav (py2180333@gmail.com)


lOMoARcPSD|31013873

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
Implement Caesar cipher encryption-decryption and
1. √
perform cryptanalysis using a brute-force approach.
2.1 Implement Playfair cipher encryption-decryption.
2. √
2.2 Implement Hill cipher encryption-decryption.
3.1 Implement Vigenere Cipher encryption-
decryption.
3. √
3.2 Implement Rail Fence Transposition cipher
technique.

4. To implement Simple DES encryption-decryption. √

5. To implement Simple AES encryption-decryption. √

6. Implement RSA encryption-decryption algorithm. √

Implement the Diffi-Hellman Key Exchange


7. √
Method.

8. Write a program to generate MD5 hash. √

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

10. Implement a digital signature algorithm. √

Tools and Case Studies

1. Study Cryptography and cryptanalysis concepts using CrypTool.

2. Case study: List 10 recent cyber attacks/data breaches and explain any one in detail.

Downloaded by pranav yadav (py2180333@gmail.com)


lOMoARcPSD|31013873

Industry Relevant Skills

The following industry-relevant competencies are expected to be developed in the student by


undertaking the practical work of this laboratory.
1. Able to think about information security scenarios and make a solution
2. Able to develop algorithms which help to secure data

Guidelines for Faculty Members


1. The teacher should provide the guidelines and demonstrate practicals to the students
with all features.
2. Before starting each practical, the teacher shall explain basic concepts/theory related to the
experiment to the students.
3. Involve all the students in the performance of each experiment.
4. The 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 after the
experimentation.
5. Teachers should give students the opportunity for hands-on experience after the
demonstration.
6. Teachers may provide additional knowledge and skills to the students even though they
are not covered in the manual but are expected from the students by the concerned
industry.
7. Give practical assignments and assess students' performance based on the assigned task
to check whether it is as per the instructions.
8. The teacher is expected to refer to the course's complete curriculum and follow the
implementation guidelines.

Instructions for Students


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

Downloaded by pranav yadav (py2180333@gmail.com)


lOMoARcPSD|31013873

Common Safety Instructions

Students are expected to,

1. Handle equipment with care: Students should handle equipment and peripherals with
care when working in the lab. This includes gently using the mouse and keyboard,
avoiding pulling or twisting network cables, and carefully handling any hardware
devices.
2. Avoid water and liquids: Students should avoid using wet hands or having fluids near the
computer equipment. This will help prevent damage to the devices and avoid any safety
hazards.
3. Shut down the PC properly: Students should shut down the computer properly at the end
of the lab session. This includes closing all programs and applications, saving any work,
and following the correct shutdown procedure for the operating system.
4. Obtain permission for laptops: If students wish to use their laptops in the lab, they
should first obtain permission from the Lab Faculty or Lab Assistant. They should
follow all lab rules and guidelines and ensure their laptop is configured correctly for the
lab environment.

Downloaded by pranav yadav (py2180333@gmail.com)


lOMoARcPSD|31013873

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 and perform cryptanalysis using
a brute-force approach.
2.1 Implement Playfair cipher encryption-
decryption.
2
2.2 Implement Hill cipher encryption-
decryption.
3.1 Implement Vigenere Cipher encryption-
decryption.
3
3.2 Implement Rail Fence Transposition
cipher technique.
To implement Simple DES encryption-
4
decryption.
To implement Simple AES encryption-
5
decryption.
Implement RSA encryption-decryption
6
algorithm.
Implement the Diffi-Hellman Key Exchange
7
Method.

8 Write a program to generate MD5 hash.

9 Write a program to generate SHA-1 hash.

10 Implement a digital signature algorithm.

Total

Downloaded by pranav yadav (py2180333@gmail.com)


lOMoARcPSD|31013873

Experiment No: 1
Implement Caesar cipher encryption-decryption and perform
cryptanalysis using a brute-force approach.
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.

Downloaded by pranav yadav (py2180333@gmail.com)


lOMoARcPSD|31013873

Program:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new
Scanner(System.in);
System.out.println("Caesar Cipher Encryption and Decryption");
System.out.print("Enter the plaintext: ");
String plaintext = scanner.nextLine();
System.out.print("Enter the key (a number between 1 and 25): ");
int key = scanner.nextInt();
// Encryption
String ciphertext = encrypt(plaintext, key);
System.out.println("Encrypted text: " +
ciphertext);
// Decryption
String decryptedText = decrypt(ciphertext, key);
System.out.println("Decrypted text: " + decryptedText);
// Cryptanalysis (Brute Force)
System.out.println("Cryptanalysis (Brute Force):");
bruteForceCryptanalysis(ciphertext);
scanner.close();
}
// Encrypts the plaintext using the Caesar cipher
public static String encrypt(String plaintext, int key) {
StringBuilder encryptedText = new StringBuilder();
for (char c : plaintext.toCharArray()) {
if (Character.isLetter(c)) {
char base = Character.isLowerCase(c) ? 'a' : 'A';
encryptedText.append((char) (((c - base + key) % 26) + base));
} else {
encryptedText.append(c);
}
}
return encryptedText.toString();
}
// Decrypts the ciphertext using the Caesar cipher
public static String decrypt(String ciphertext, int key) {
return encrypt(ciphertext, 26 - key);
}
// Perform cryptanalysis using brute-force approach
public static void bruteForceCryptanalysis(String ciphertext) {
for (int key = 1; key <= 25; key++) {
System.out.println("Key " + key + ": " + decrypt(ciphertext, key));
}
}
Downloaded by pranav yadav (py2180333@gmail.com)
lOMoARcPSD|31013873

Downloaded by pranav yadav (py2180333@gmail.com)


lOMoARcPSD|31013873

Output:

Conclusion:

In conclusion, this Java program provides a practical implementation of the Caesar cipher for both
encryption and decryption. It also demonstrates the vulnerability of the Caesar cipher to brute-force
cryptanalysis, emphasizing the importance of using more secure encryption methods for sensitive
data.

Quiz:

1. Is Ceaser Cipher Symmetric or Asymmetric Algorithm?

 Symmetric Algorithm

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

 Original: a l p h a b e t
Encrypted: d o s k d e h
w

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

References used by the students:


 https://www.javatpoint.com/caesar-cipher-program-in-java

Rubric wise marks obtained:

Rubrics 1 2 3 4 5 Total
Marks

Downloaded by pranav yadav (py2180333@gmail.com)


lOMoARcPSD|31013873

Experiment No: 2
2.1 Implement Playfair cipher encryption-decryption.

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:

Downloaded by pranav yadav (py2180333@gmail.com)


lOMoARcPSD|31013873

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:

import java.util.ArrayList;
import java.util.List;

public class PlayfairCipher {


private final char[][]
keyMatrix;

public PlayfairCipher(String key) {


keyMatrix =
generateKeyMatrix(key);
}
private char[][] generateKeyMatrix(String key) {
String cleanedKey = key.replaceAll("\\s", "").toUpperCase();
char[][] matrix = new char[5][5];
String alphabet =
"ABCDEFGHIKLMNOPQRSTUVWXYZ"; int row = 0, col
= 0;
for (char c : cleanedKey.toCharArray()) {
if (!contains(matrix, c)) {
matrix[row][col] = c;
col++;
if (col == 5) {
col = 0;
row++;
}
}
}
for (char c : alphabet.toCharArray())
{ if (!contains(matrix, c)) {
matrix[row][col] = c;
col++;
Downloaded by pranav yadav (py2180333@gmail.com)
lOMoARcPSD|31013873

if (col == 5) {
col = 0;

Downloaded by pranav yadav (py2180333@gmail.com)


lOMoARcPSD|31013873

row++;
}
}
}
return matrix;
}
private boolean contains(char[][] matrix, char c) {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (matrix[i][j] == c) {
return true;
}
}
}
return false;
}
private String normalizePlainText(String text) {
String cleanedText = text.replaceAll("[^A-Z]", "").toUpperCase();
StringBuilder normalizedText = new StringBuilder(cleanedText);
for (int i = 1; i < normalizedText.length(); i += 2) {
if (normalizedText.charAt(i) == normalizedText.charAt(i - 1)) {
normalizedText.insert(i, 'X');
}
}
if (normalizedText.length() % 2 != 0) {
normalizedText.append('X');
}
return normalizedText.toString();
}
public String encrypt(String plaintext) {
StringBuilder ciphertext = new
StringBuilder();
String normalizedText = normalizePlainText(plaintext);
for (int i = 0; i < normalizedText.length(); i += 2) {
char a = normalizedText.charAt(i);
char b = normalizedText.charAt(i + 1);
int[] aPos = findPosition(a);
int[] bPos = findPosition(b);
if (aPos[0] == bPos[0]) { // Same row
ciphertext.append(keyMatrix[aPos[0]][(aPos[1] + 1) %
5]);
ciphertext.append(keyMatrix[bPos[0]][(bPos[1] + 1) % 5]);
} else if (aPos[1] == bPos[1]) { // Same column
ciphertext.append(keyMatrix[(aPos[0] + 1) % 5][aPos[1]]);
ciphertext.append(keyMatrix[(bPos[0] + 1) % 5][bPos[1]]);

Downloaded by pranav yadav (py2180333@gmail.com)


lOMoARcPSD|31013873

} else { // Different row and column


ciphertext.append(keyMatrix[aPos[0]][bPos[1]]);

Downloaded by pranav yadav (py2180333@gmail.com)


lOMoARcPSD|31013873

ciphertext.append(keyMatrix[bPos[0]][aPos[1]]);
}
}
return ciphertext.toString();
}
public String decrypt(String ciphertext) {
StringBuilder plaintext = new StringBuilder();
for (int i = 0; i < ciphertext.length(); i += 2) {
char a = ciphertext.charAt(i);
char b = ciphertext.charAt(i + 1);
int[] aPos = findPosition(a);
int[] bPos = findPosition(b);
if (aPos[0] == bPos[0]) { // Same row plaintext.append(keyMatrix[aPos[0]]
[(aPos[1] + 4) % 5]);
plaintext.append(keyMatrix[bPos[0]][(bPos[1] + 4) % 5]);
} else if (aPos[1] == bPos[1]) { // Same column
plaintext.append(keyMatrix[(aPos[0] + 4) % 5][aPos[1]]);
plaintext.append(keyMatrix[(bPos[0] + 4) % 5][bPos[1]]);
} else { // Different row and column
plaintext.append(keyMatrix[aPos[0]][bPos[1]]);
plaintext.append(keyMatrix[bPos[0]][aPos[1]]);
}
}
return plaintext.toString();
}
private int[] findPosition(char c) {
int[] position = new int[2];
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++)
{
if (keyMatrix[i][j] == c) {
position[0] = i;
position[1] = j;
return position;
}
}
}
return position;
}
public static void main(String[] args) {
PlayfairCipher cipher = new PlayfairCipher("KEYWORD");
String plaintext = "VGEC";
String encryptedText = cipher.encrypt(plaintext);
String decryptedText = cipher.decrypt(encryptedText);

System.out.println("Original Text: " + plaintext);


Downloaded by pranav yadav (py2180333@gmail.com)
lOMoARcPSD|31013873

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


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

Output:

Conclusion:

The Playfair cipher encryption algorithm is a historical cryptographic technique that offers a
moderate level of security for text-based communication. It is based on the use of a 5x5 key matrix,
which is generated from a keyword and used to encrypt plaintext by substituting letter pairs
(bigrams) with corresponding ciphertext pairs.

Quiz:

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

True

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

References used by the students:

 https://chat.openai.com/c/02d539c2-4d78-4c1f-9bdf-2aae31e0db84
 https://www.javatpoint.com/playfair-cipher-program-in-java

Rubric wise marks obtained:

Rubrics 1 2 3 4 5 Total
Marks

Downloaded by pranav yadav (py2180333@gmail.com)


lOMoARcPSD|31013873

3170720 INFORMATION SECURITY

Experiment No: 2
2.2 Implement Hill cipher encryption-decryption.

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.Scanner;

public class HillCipher {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Define the 2x2 key matrix for encryptionVGE
int[][] keyMatrix = {
{3, 5},
{2, 7}
};
// Prompt the user for input text
System.out.print("Enter the plaintext (uppercase only): ");
String plaintext = scanner.nextLine();
plaintext = plaintext.replaceAll("[^A-Z]", ""); // Remove non-alphabet characters
plaintext = padPlaintext(plaintext, 2); // Ensure the plaintext length is a multiple of
2
// Encrypt the plaintext
String ciphertext = encrypt(plaintext, keyMatrix);
// Decrypt the ciphertext
String decryptedText = decrypt(ciphertext, keyMatrix);
System.out.println("Plaintext: " + plaintext);
System.out.println("Ciphertext: " + ciphertext);
}
Downloaded by pranav yadav (py2180333@gmail.com)
lOMoARcPSD|31013873

3170720 INFORMATION SECURITY

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


scanner.close();

}
Downloaded by pranav yadav (py2180333@gmail.com)
lOMoARcPSD|31013873

// Encrypt a block of text using the Hill cipher


public static String encrypt(String plaintext, int[][] keyMatrix) {
StringBuilder ciphertext = new StringBuilder();
int blockSize = keyMatrix.length;
for (int i = 0; i < plaintext.length(); i += blockSize) {
String block = plaintext.substring(i, i + blockSize);
for (int j = 0; j < blockSize; j++) {
int sum = 0;
for (int k = 0; k < blockSize; k++) {
int plainChar = block.charAt(k) - 'A';
sum += keyMatrix[j][k] * plainChar;
}
char encryptedChar = (char) ((sum % 26) + 'A');
ciphertext.append(encryptedChar);
}
}
return ciphertext.toString();
}
// Decrypt a block of text using the Hill cipher
public static String decrypt(String ciphertext, int[][] keyMatrix) {
StringBuilder decryptedText = new StringBuilder();
int blockSize = keyMatrix.length;
int det = keyMatrix[0][0] * keyMatrix[1][1] - keyMatrix[0][1] * keyMatrix[1][0];
int detInv = modInverse(det, 26);

int adj11 = keyMatrix[1][1];


int adj22 = keyMatrix[0][0];

keyMatrix[0][0] = adj11;
keyMatrix[1][1] = adj22;
keyMatrix[0][1] *= -1;
keyMatrix[1][0] *= -1;

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


for (int j = 0; j < blockSize; j++) {
keyMatrix[i][j] = (keyMatrix[i][j] * detInv % 26 + 26) % 26;
}
}

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


String block = ciphertext.substring(i, i + blockSize);
for (int j = 0; j < blockSize; j++) {
int sum = 0;
for (int k = 0; k < blockSize; k++) {
int cipherChar = block.charAt(k) - 'A';
sum += keyMatrix[j][k] * cipherChar;
}
char decryptedChar = (char) ((sum % 26) + 'A');
decryptedText.append(decryptedChar);
}
}

return decryptedText.toString();
}
public static String padPlaintext(String plaintext, int blockSize) {
int padding = blockSize - (plaintext.length() % blockSize);
if (padding != blockSize) {
for (int i = 0; i < padding; i++) {
plaintext += 'X';
}
}

Downloaded by pranav yadav (py2180333@gmail.com)


lOMoARcPSD|31013873

return plaintext;

Downloaded by pranav yadav (py2180333@gmail.com)


lOMoARcPSD|31013873

3170720 INFORMATION SECURITY

// Calculate the modular multiplicative inverse


public static int modInverse(int a, int m) {
for (int x = 1; x < m; x++) {
if ((a * x) % m == 1) {
return x;
}
}
return -1;
}
}

Output:

Conclusion:

The Hill cipher encryption-decryption algorithm is a fascinating example of polygraphic substitution


ciphers in classical cryptography. It offers a more complex and secure method of encrypting and
decrypting messages compared to simple substitution ciphers.

Quiz:

1. What preliminary knowledge required for Hill cipher ?

 Matrix algebra.

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

 Polygraphic substitution cipher

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

References used by the students:

 https://www.javatpoint.com/hill-cipher-program-in-java

Rubric wise marks obtained:

Rubrics 1 2 3 4 5 Total
Marks

Downloaded by pranav yadav (py2180333@gmail.com)


lOMoARcPSD|31013873

3170720 INFORMATION SECURITY

Experiment No: 3
3.1 Implement Vigenere Cipher encryption-decryption.

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:

Downloaded by pranav yadav (py2180333@gmail.com)


lOMoARcPSD|31013873

3170720 INFORMATION SECURITY

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 isattached 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 withthat of the plain
text.
STEP-6: Pick the first letter of the plain text and that of the keyword as the row indicesand 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:

public class VigenereCipher {


public static String encrypt(String plaintext, String key) {
StringBuilder ciphertext = new StringBuilder();
plaintext = plaintext.toUpperCase();
key = key.toUpperCase();

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


{ char c = plaintext.charAt(i);
if (c >= 'A' && c <= 'Z') {
int shift = key.charAt(j) - 'A';
char encryptedChar = (char) ((c + shift - 'A') % 26 + 'A');
ciphertext.append(encryptedChar);
j = (j + 1) % key.length();
} else {
ciphertext.append(c);
}
}
return ciphertext.toString();
}
public static String decrypt(String ciphertext, String key) {
StringBuilder plaintext = new StringBuilder();
ciphertext = ciphertext.toUpperCase();
key = key.toUpperCase();
for (int i = 0, j = 0; i < ciphertext.length(); i++) {
char c = ciphertext.charAt(i);
if (c >= 'A' && c <= 'Z') {
int shift = key.charAt(j) - 'A';
char decryptedChar = (char) ((c - shift - 'A' + 26) % 26 + 'A');
plaintext.append(decryptedChar);
j = (j + 1) % key.length();
} else {
plaintext.append(c);
}
}

Downloaded by pranav yadav (py2180333@gmail.com)


lOMoARcPSD|31013873

3170720 INFORMATION SECURITY

return plaintext.toString();
}

Downloaded by pranav yadav (py2180333@gmail.com)


lOMoARcPSD|31013873

3170720 INFORMATION SECURITY

public static void main(String[] args) {


String plaintext = "VGEC";
String key = "KEY";
String encryptedText = encrypt(plaintext, key);
String decryptedText = decrypt(encryptedText, key);
System.out.println("Original Text: " + plaintext);
System.out.println("Encrypted Text: " + encryptedText);
System.out.println("Decrypted Text: " + decryptedText);
}
}

Output:

Conclusion:

The Vigenere Cipher is a classical encryption technique that employs a variable-length key to
encrypt and decrypt messages, adding an extra layer of security compared to simpler substitution
ciphers. This Java implementation provides a practical way to apply the Vigenere Cipher for secure
communication while handling non-alphabetic characters within the text

Quiz:

1. Encryption in Vigenere cipher is done using …..

Encryption in Vigenere cipher is done using a repeating key to shift each character in the plaintext by a
corresponding amount, creating a more complex and secure form of substitution encryption.

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

References used by the students:

 https://www.geeksforgeeks.org/vigenere-cipher/

Rubric wise marks obtained:

Rubrics 1 2 3 4 5 Total
Marks

Downloaded by pranav yadav (py2180333@gmail.com)


lOMoARcPSD|31013873

3170720 INFORMATION SECURITY

3.2 Implement Rail Fence Transposition cipher technique.


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 correspondingcolumns of the
plain text.

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

Program:

public class RailFenceCipher {


// Encrypts a plaintext using the Rail Fence Transposition cipher
public static String encrypt(String plaintext, int rails) {
StringBuilder[] fence = new StringBuilder[rails];
for (int i = 0; i < rails; i++) {
fence[i] = new StringBuilder();
}

Downloaded by pranav yadav (py2180333@gmail.com)


lOMoARcPSD|31013873

3170720 INFORMATION SECURITY

int rail = 0;
int direction = 1; // 1 for down, -1 for up
for (char c : plaintext.toCharArray()) {
fence[rail].append(c);

if (rail == 0) {
direction = 1;
} else if (rail == rails - 1) {
direction = -1;
}
rail += direction;
}
StringBuilder ciphertext = new StringBuilder();
for (StringBuilder railString : fence) {
ciphertext.append(railString.toString());
}
return ciphertext.toString();
}
// Decrypts a ciphertext using the Rail Fence Transposition cipher
public static String decrypt(String ciphertext, int rails) {
StringBuilder[] fence = new StringBuilder[rails];
for (int i = 0; i < rails; i++) {
fence[i] = new
StringBuilder();
}
int rail = 0;
int direction = 1;
for (char c : ciphertext.toCharArray()) {
fence[rail].append('*'); // Placeholder
character if (rail == 0) {
direction = 1;
} else if (rail == rails - 1) {
direction = -1;
}
rail += direction;
}
int index = 0;
for (int i = 0; i < rails; i++) {
int length =
fence[i].length();
for (int j = 0; j < length; j++) {
fence[i].setCharAt(j, ciphertext.charAt(index++));
}
}
rail = 0;
direction = 1;
StringBuilder plaintext = new StringBuilder();

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


plaintext.append(fence[rail].charAt(0));
fence[rail].deleteCharAt(0);

if (rail == 0) {
direction = 1;

Downloaded by pranav yadav (py2180333@gmail.com)


lOMoARcPSD|31013873

3170720 INFORMATION SECURITY

} else if (rail == rails - 1) {


direction = -1;
}
rail += direction;
}

Downloaded by pranav yadav (py2180333@gmail.com)


lOMoARcPSD|31013873

3170720 INFORMATION SECURITY

return plaintext.toString();
}

public static void main(String[] args) {


String plaintext = "CE VGEC";
int rails = 3;
String encryptedText = encrypt(plaintext, rails);
System.out.println("Encrypted: " + encryptedText);

String decryptedText = decrypt(encryptedText, rails);


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

Output:

Conclusion:

The Rail Fence Transposition cipher in Java provides a basic encryption and decryption mechanism,
useful for educational purposes but not suitable for secure data protection due to its vulnerability to
cryptographic attacks. For stronger security, modern encryption methods should be employed.

Quiz:

1. Encryption in Rail fence cipher is done using


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

2. Rail fence cipher is more secure than one time pad cipher? True/False
False

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

References used by the students:


 https://www.geeksforgeeks.org/rail-fence-cipher-encryption-decryption/

Rubric wise marks obtained:

Rubrics 1 2 3 4 5 Total
Marks

Downloaded by pranav yadav (py2180333@gmail.com)

You might also like