0% found this document useful (0 votes)
19 views47 pages

Is Lab Manual Final

The document is a laboratory manual for the Information Security course, detailing practical experiments for B.E. Semester 6 students in Computer Engineering. It includes implementations of various encryption techniques such as Caesar cipher, Playfair cipher, and Hill cipher, along with their theoretical foundations, algorithms, and programming examples. The manual also features quizzes, conclusions, and references for further study.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views47 pages

Is Lab Manual Final

The document is a laboratory manual for the Information Security course, detailing practical experiments for B.E. Semester 6 students in Computer Engineering. It includes implementations of various encryption techniques such as Caesar cipher, Playfair cipher, and Hill cipher, along with their theoretical foundations, algorithms, and programming examples. The manual also features quizzes, conclusions, and references for further study.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 47

INFORMATION SECURITY (3164603) 230173146008

A Laboratory Manual for

Information Security
(3164603)

B.E. Semester 6(Computer Science


& Engineering(Data Science))

Directorate of Technical Education, Gandhinagar,


Gujarat
INFORMATION SECURITY (3164603) 230173146008

Vishwakarma Government Engineering


College
Department of Computer Engineering

CERTIFICATE

This is to certify that Ms.Priyanshi H. Desai Enrollment

No. 230173146008 of B.E. Semester 6 from Computer Engineering

Science & Engineering (Data Science) Department of this Institute

(GTU Code: 017) has satisfactorily completed the Practical /

Tutorial work for the subject Information Security (3164603) for the

academic year 2024-25.

Place:

Date:

Signature of Course Faculty Head of the


Department
INFORMATION SECURITY (3164603) 230173146008

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 Caesar 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 "wraparound". W becomes Z, X becomes A, Y becomes oB, 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.

Program:
def encrypt(plain_txt, key):
cipher_txt = ""

for i in range(len(plain_txt)):
char = plain_txt[i]
if char.isupper():
cipher_txt += chr((ord(char) + key - 65) % 26 + 65)
elif char.islower():
cipher_txt += chr((ord(char) + key - 97) % 26 + 97)
else:
INFORMATION SECURITY (3164603) 230173146008

cipher_txt += char

return cipher_txt

def decrypt(cipher_txt, key):


plain_txt = ""

for i in range(len(cipher_txt)):
char = cipher_txt[i]
if char.isupper():
plain_txt += chr((ord(char) - key - 65) % 26 + 65)
elif char.islower():
plain_txt += chr((ord(char) - key - 97) % 26 + 97)
else:
plain_txt += char

return plain_txt

plain_txt = input("Enter any plain text: ")


key = int(input("Enter key value: "))

if key < 1 or key > 25:


print("Enter valid key value (between 1 & 25)")
else:
print("The Cipher text: ", encrypt(plain_txt,key))
print("Original plain text:", decrypt(encrypt(plain_txt, key), key))

cipher = input("Enter any cipher text: ")


for i in range(1, 26):
print(f"Key: {i}, Plain text: {decrypt(cipher, i)}")

Output:
INFORMATION SECURITY (3164603) 230173146008

Conclusion: The Caesar cipher is a simple substitution cipher where each letter in the plaintext is
shifted a certain number of places down the alphabet. The number of positions shifted is the "key" of
the cipher. This method is named after Julius Caesar, who used it to encrypt his messages.

Quiz:

1. Is Caesar Cipher Symmetric or Asymmetric Algorithm?


Ans. The Caesar Cipher is a symmetric encryption algorithm. In symmetric encryption, the same key
is used for both encryption and decryption. With the Caesar Cipher, the shift value used to encrypt
the message is the same key that's used to decrypt it by shifting in the opposite direction.

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


Ans. a->d, l->o, p->s, h->k, a->d, b->e, e->h, t->w
So, "alphabet" encrypted with a Caesar cipher and a shift of 3 becomes "dos dew".

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
INFORMATION SECURITY (3164603) 230173146008

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 ofPlayfair 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 beunique 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 "HELLO WORLD", 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. Then apply the following 4 rules, inorder, to each
pair of letters in the plain text:
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 letter
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:

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’
INFORMATION SECURITY (3164603) 230173146008

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:
from re import sub

def prepare_key(key):
"""Prepares the key by removing duplicates and non-alphabetic characters """
key = key.upper()
key = "".join(dict.fromkeys(key)) # Remove duplicates while preserving order
if 'J' in key:
key = key.replace('J', 'I') # I and J are treated as the same
return key

def create_matrix(key):
"""Creates the 5x5 Playfair matrix from the key."""
matrix = list(key)
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # I/J combined

for char in alphabet:


if char not in matrix:
matrix.append(char)

print("The matrix key:")


for i in range(0, 25, 5):
print(matrix[i : i + 5])

return [matrix[i:i+5] for i in range(0, 25, 5)]

def find_position(matrix, char):


"""Finds the row and column of a character in the matrix."""
for i in range(5):
for j in range(5):
if matrix[i][j] == char:
return i, j
# raise ValueError(f"Character '{char}' not found in matrix")

def encrypt_pair(matrix, a, b):


"""Encrypts a digraph (pair of letters)."""
row1, col1 = find_position(matrix, a) # type: ignore
row2, col2 = find_position(matrix, b) # type: ignore

if row1 == row2: # Same row


return matrix[row1][(col1 + 1) % 5], matrix[row2][(col2 + 1) % 5]
elif col1 == col2: # Same column
return matrix[(row1 + 1) % 5][col1], matrix[(row2 + 1) % 5][col2]
else: # Rectangle
return matrix[row1][col2], matrix[row2][col1]

def decrypt_pair(matrix, a, b):


"""Decrypts a digraph (pair of letters)."""
row1, col1 = find_position(matrix, a) # type: ignore
row2, col2 = find_position(matrix, b) # type: ignore

if row1 == row2: # Same row


return matrix[row1][(col1 - 1) % 5], matrix[row2][(col2 - 1) % 5]
elif col1 == col2: # Same column
INFORMATION SECURITY (3164603) 230173146008

return matrix[(row1 - 1) % 5][col1], matrix[(row2 - 1) % 5][col2]


else: # Rectangle
return matrix[row1][col2], matrix[row2][col1]

def process_text(text):
"""Prepares the plaintext for encryption/decryption."""
text = "".join(c.upper() for c in text if c.isalpha())
text = text.replace('J', 'I')
# text = sub(r"(.)\1", r"\1X\1", text) # Add 'X' between double letters
if len(text) % 2 != 0:
text += 'X' # Pad with 'X' if odd length
return text

def playfair_cipher(text, key, mode='enc'):


"""Performs Playfair cipher encryption or decryption."""
key = prepare_key(key)
matrix = create_matrix(key)
text = process_text(text)

result = ""
for i in range(0, len(text), 2):
a = text[i]
b = text[i+1]
if mode == 'enc':
c, d = encrypt_pair(matrix, a, b)
elif mode == 'dec':
c, d = decrypt_pair(matrix, a, b)
else:
raise ValueError("Invalid mode. Choose 'enc' or 'dec'")
result += c + d

return result

plaintext = input("Enter plain text: ")


key = input("Enter key: ")

ciphertext = playfair_cipher(plaintext, key, 'enc')


print("Cipher text:", ciphertext)

decrypted_text = playfair_cipher(ciphertext, key, 'dec')


if decrypted_text[-1] == 'X':
decrypted_text = decrypted_text[:-1]

print("Decrypted text:", decrypted_text)

Output:
INFORMATION SECURITY (3164603) 230173146008

Conclusion: The Playfair cipher is a manual symmetric encryption technique that uses a 5x5 grid of
letters to substitute pairs of letters in the plaintext with different pairs of letters. It was invented by
Charles Wheatstone in 1854 and is considered one of the first digraph substitution ciphers, making it
more secure than simple substitution ciphers.

Quiz:

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


True. Because of: It uses a polygraphic substitution method, where pairs of letters are replaced by
other pairs of letters. Increased complexity; It is less susceptible to frequency analysis attacks.

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
INFORMATION SECURITY (3164603) 230173146008

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 ofHill 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 matrix used for encryption. The matrix used for
encryption is the cipher key, and it shold 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 key word 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 numpy as np

def keyMat(key, n):


kmat = np.empty((n, n), dtype=object)
kmat.fill('X')
k=0
for i in range(n):
for j in range(n):
INFORMATION SECURITY (3164603) 230173146008

if k < len(key):
kmat[i][j] = ord(key[k]) % 65
k += 1
else:
kmat[i][j] = ord(kmat[i][j]) % 65

return kmat

def hill_cipher_encrypt(plaintext, key_matrix):


key_dim = key_matrix.shape[0]

if len(plaintext) % key_dim != 0:
plaintext += 'X' * (key_dim - (len(plaintext) % key_dim))
# print(f"Error: Plaintext length must be a multiple of {key_dim}.")
# return None

ciphertext = ""
for i in range(0, len(plaintext), key_dim):
block = [ord(char) - 65 for char in plaintext[i:i + key_dim]] # Convert to numerical values (0-25)
block_matrix = np.array(block).reshape(key_dim, 1) # Reshape into a column vector

encrypted_block = np.dot(key_matrix, block_matrix) % 26

for j in range(key_dim):
ciphertext += chr(int(encrypted_block[j, 0]) + 65) # Convert back to characters

return ciphertext

def hill_cipher_decrypt(ciphertext, key_matrix):


key_dim = key_matrix.shape[0]

# Calculate the modular inverse of the key matrix


det = int(round(np.linalg.det(key_matrix))) # Integer determinant
det_inv = -1 # Initialize
for i in range(26):
if (det * i) % 26 == 1:
det_inv = i
break

if det_inv == -1:
print("Error: Key matrix is not invertible (mod 26).")
return None

adjugate_matrix = np.round(det * np.linalg.inv(key_matrix) * det_inv) % 26 # Adjugate and modular inverse

plaintext = ""
for i in range(0, len(ciphertext), key_dim):
block = [ord(char) - 65 for char in ciphertext[i:i + key_dim]]
block_matrix = np.array(block).reshape(key_dim, 1)

decrypted_block = np.dot(adjugate_matrix, block_matrix) % 26

for j in range(key_dim):
plaintext += chr(int(decrypted_block[j, 0]) + 65)

return plaintext

# Driver Code
key_str = input("Enter the key: ").upper()
INFORMATION SECURITY (3164603) 230173146008

plaintext = input("Enter the Plain text: ").upper() # meet meat the usual place

# # To get size of matrix that just accommodate the key


n=2
while len(key_str) > n*n:
n += 1

key_matrix = keyMat(key_str, n)
print("The Key matrix:\n", key_matrix)

ciphertext = hill_cipher_encrypt(plaintext, key_matrix)


print("Ciphertext:", ciphertext)

decrypted_text = hill_cipher_decrypt(ciphertext, key_matrix.astype("int"))


print("Decrypted text:", decrypted_text)

Output:

Conclusion: The Hill cipher is a polygraphic substitution cipher that uses matrix multiplication to
encrypt and decrypt messages, based on a key matrix chosen by the user. It is a block cipher that
operates on groups of letters, making it more secure than simple substitution ciphers but vulnerable
to frequency analysis and known-plaintext attacks.

Quiz:
1. What preliminary knowledge required for Hill cipher ?
To understand the Hill cipher, you should have preliminary knowledge of:
Matrix algebra (addition, multiplication, and inverse)
Modular arithmetic (operations with remainders)
Basic cryptography concepts (substitution, encryption, decryption)

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


The Hill cipher is an example of a polygraphic substitution cipher technique, which is a type of
block cipher.

Suggested Reference:
1. https://crypto.interactive-maths.com/hill-cipher.html
References used by the students:
https://crypto.interactive-maths.com/hill-cipher.html

Rubric wise marks obtained:


INFORMATION SECURITY (3164603) 230173146008

Rubrics 1 2 3 4 5 Total
Marks

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 ofVigenere 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 of the alphabet written out 26 times in differnt 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
along 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:
INFORMATION SECURITY (3164603) 230173146008

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:
def generate_key(msg, key):
if len(msg) == len(key):
return key
else:
key = key * (len(msg) // len(key))
key += key[:len(msg) % len(key)]
return key

def encrypt_vigenere(msg, key):


cipher_text = []
key = generate_key(msg, key)
for i in range(len(msg)):
char = msg[i]
if char.isupper():
encrypted_char = chr((ord(char) + ord(key[i]) - 2 * 65) % 26 + 65)
elif char.islower():
encrypted_char = chr((ord(char) + ord(key[i]) - 2 * 97) % 26 + 97)
else:
encrypted_char = char
cipher_text.append(encrypted_char)
return "".join(cipher_text)
INFORMATION SECURITY (3164603) 230173146008

def decrypt_vigenere(msg, key):


decrypted_text = []
key = generate_key(msg, key)
for i in range(len(msg)):
char = msg[i]
if char.isupper():
decrypted_char = chr((ord(char) - ord(key[i]) + 26) % 26 + 65)
elif char.islower():
decrypted_char = chr((ord(char) - ord(key[i]) + 26) % 26 + 97)
else:
decrypted_char = char
decrypted_text.append(decrypted_char)
return "".join(decrypted_text)

plain_text = input("Enter plaint text: ")


key = input("Enter the key: ")

cipher_text = encrypt_vigenere(plain_text, key)


print(f"Encrypted Text: {cipher_text}")

decrypted_text = decrypt_vigenere(cipher_text, key)


print(f"Decrypted Text: {decrypted_text}")

Output:

Conclusion: The Vigenère cipher is a polyalphabetic substitution cipher that uses a keyword to
encrypt and decrypt messages by shifting each letter by a corresponding letter in the keyword. This
cipher is considered more secure than monoalphabetic ciphers, such as the Caesar cipher, due to its
use of a keyword to create a unique substitution for each letter.

Quiz:
1. Encryption in Vigenere cipher is done using _____________?
A. Encryption in the Vigenère cipher is done using a polyalphabetic substitution method, where each
letter of the plaintext is shifted by a corresponding letter of the keyword. The shift is determined by
the alphabetical position of the keyword letter, with A=0, B=1, C=2, and so on.

Suggested Reference:
1. https://intellipaat.com/blog/vigenere-cipher/
References used by the students:
https://intellipaat.com/blog/vigenere-cipher/
geeksforgeeks/vigenere-cipher

Rubric wise marks obtained:


INFORMATION SECURITY (3164603) 230173146008

Rubrics 1 2 3 4 5 Total
Marks

Experiment No: 3

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 ofRail 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 plain text is written out. The message is
then read off in rows.
Example:
INFORMATION SECURITY (3164603) 230173146008

Algorithm:
STEP-1: Read the Plain text.
STEP-2: Arrange the plain text in row column 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 the cipher text.

Program:
def encrypt_railfence(plain_text, key):
rail = [ ['_' for _ in range(len(plain_text)) ]
for _ in range(key)]

# to find the direction


dir_down = False
row, col = 0, 0

for i in range(len(plain_text)):
# check the direction of flow; reverse the direction if we've just filled the top or bottom rail
if (row == 0) or (row == key - 1):
dir_down = not dir_down

# fill the corresponding alphabet


rail[row][col] = plain_text[i]
col += 1

# find the next row using direction flag


if dir_down:
row += 1
else:
row -= 1

# now we can construct the cipher using the rail matrix


cipher = ""
for i in range(key):
for j in range(len(plain_text)):
if rail[i][j] != '_':
cipher += rail[i][j]

return cipher
INFORMATION SECURITY (3164603) 230173146008

def decrypt_railfence(cipher_text, key):


rail = [ ['_' for _ in range(len(cipher_text)) ]
for _ in range(key)]

# to find the direction


dir_down = False
row, col = 0, 0

# mark the diagonal places with '*'


for i in range(len(cipher_text)):
if (row == 0) or (row == key - 1):
dir_down = not dir_down

# place the marker


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

# find the next row using direction flag


if dir_down:
row += 1
else:
row -= 1

# now we can construct & fill the rail matrix


index = 0
for i in range(key):
for j in range(len(cipher_text)):
if ((rail[i][j] == '*') and (index < len(cipher_text))):
rail[i][j] = cipher_text[index]
index += 1

# now read the matrix in zig-zag manner to get the original/plain text
plain = ""
dir_down = False
row, col = 0, 0
for i in range(len(cipher_text)):
# check the direction of flow
if (row == 0) or (row == key - 1):
dir_down = not dir_down

# insert the letter to plain str


if (rail[row][col] != '_'):
plain += rail[row][col]
col += 1

# find the next row using direction flag


if dir_down:
row += 1
else:
row -= 1

return plain

plain = input("Enter the plain text: ")


key = int(input("Enter the key: "))

cipher = encrypt_railfence(plain, key)


print(f"Cipher text is: {cipher}")
print(f"Plain text is: {decrypt_railfence(cipher, key)}")

Output:
INFORMATION SECURITY (3164603) 230173146008

Conclusion: The Rail Fence Transposition Cipher is a type of transposition cipher that rearranges
the plaintext by writing it in a zigzag pattern across a series of rails, then reading it off in rows. This
cipher is relatively simple to implement but can be challenging to decipher without knowledge of the
number of rails used.

Quiz:
1. Encryption in Rail fence cipher is done using __(a)___
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

2. Rail fence cipher is more secure than one time pad cipher? True/False
A. False. The Rail Fence Cipher is a relatively simple transposition cipher, and it is not considered to be
as secure as the One-Time Pad (OTP) cipher. The OTP cipher is considered to be theoretically
unbreakable, as long as the key is truly random, never reused, and kept secret. The Rail Fence Cipher,
on the other hand, can be broken using frequency analysis and other cryptanalytic techniques,
especially if the key (i.e., the number of rails) is small or known.

Suggested Reference:
1. https://crypto.interactive-maths.com/rail-fence-cipher.html
References used by the students:
https://crypto.interactive-maths.com/rail-fence-cipher.html

Rubric wise marks obtained:

Rubrics 1 2 3 4 5 Total
Marks

Experiment No: 4

To implement Simple DES encryption-decryption.


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 ofDES encryption-decryption.
Equipment/Instruments: Computer System, Turbo-c/ JDK
Theory: DES is asymmetric 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
INFORMATION SECURITY (3164603) 230173146008

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 2 56
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.
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:
def permute(bits, permutation_table):
"""Permutes the given bits according to the permutation table."""
return [bits[i - 1] for i in permutation_table]

def shift_left(bits, shifts):


"""Shifts the given bits left by the specified number of shifts."""
return bits[shifts:] + bits[:shifts]

def xor(bits1, bits2):


"""Performs XOR operation on two bit strings."""
return [b1 ^ b2 for b1, b2 in zip(bits1, bits2)]
INFORMATION SECURITY (3164603) 230173146008

def s_box_lookup(block, s_box):


"""Performs S-box lookup."""
row = int(str(block[0]) + str(block[5]), 2)
col = int(str(block[1]) + str(block[2]) + str(block[3]) + str(block[4]), 2)
return bin(s_box[row][col])[2:].zfill(4)

def f_function(right, key):


"""The f function of DES."""
expansion_table = [32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11, 12, 13, 12, 13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20,
21, 22, 23, 24, 25, 24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1]
s_boxes = [
[[14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7],
[0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8],
[4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0],
[15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13]],
[[15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10],
[3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5],
[0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15],
[13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9]],
[[10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8],
[13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1],
[13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7],
[1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12]],
[[7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15],
[13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9],
[10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4],
[3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14]],
[[2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9],
[14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6],
[4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14],
[11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3]],
[[12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11],
[10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8],
[9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6],
[4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13]],
[[4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1],
[13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6],
[1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2],
[6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12]],
[[13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7],
[1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2],
[7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8],
[2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11]]
]
p_table = [16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25]

expanded = permute(right, expansion_table)


xored = xor(expanded, key)
s_box_results = []
for i in range(8):
s_box_input = xored[i * 6:(i + 1) * 6]
s_box_results.extend(list(map(int, s_box_lookup(s_box_input, s_boxes[i]))))

return permute(s_box_results, p_table)

def generate_subkeys(key):
"""Generates 16 subkeys from the given key."""
pc1_table = [57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63,
55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4]
pc2_table = [14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30,
40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32]
INFORMATION SECURITY (3164603) 230173146008

shifts = [1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1]

pc1_key = permute(key, pc1_table)


left = pc1_key[:28]
right = pc1_key[28:]
subkeys = []

for shift in shifts:


left = shift_left(left, shift)
right = shift_left(right, shift)
subkey = permute(left + right, pc2_table)
subkeys.append(subkey)

return subkeys

def des(message, key, decrypt=False):


"""DES encryption/decryption."""
ip_table = [58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32,
24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15,
7]
fp_table = [40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31, 38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21,
61, 29, 36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27, 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25]

message = permute(message, ip_table)


left = message[:32]
right = message[32:]
subkeys = generate_subkeys(key)

if decrypt:
subkeys = reversed(subkeys)

for subkey in subkeys:


temp = right
right = xor(left, f_function(right, subkey))
left = temp

ciphertext = permute(right + left, fp_table)


return ciphertext

def string_to_bits(text):
"""Converts a string to a list of bits."""
bits = []
for char in text:
bits.extend(list(map(int, bin(ord(char))[2:].zfill(8))))
return bits

def bits_to_string(bits):
"""Converts a list of bits to a string."""
text = ''
for i in range(0, len(bits), 8):
byte = bits[i:i + 8]
text += chr(int(''.join(map(str, byte)), 2))
return text

def des_encrypt(plaintext, key):


"""Encrypts plaintext using DES."""
plaintext_bits = string_to_bits(plaintext)
key_bits = string_to_bits(key)
key_bits = key_bits[:64] #use only first 64 bits of the key.
if len(key_bits) < 64:
key_bits.extend([0] * (64 - len(key_bits))) #pad with zeros if key is less than 64 bits.
INFORMATION SECURITY (3164603) 230173146008

padding = 64 - (len(plaintext_bits) % 64)


if padding != 64:
plaintext_bits.extend([0] * padding)

ciphertext_bits = []
for i in range(0, len(plaintext_bits), 64):
block = plaintext_bits[i:i + 64]
ciphertext_bits.extend(des(block, key_bits))

return bits_to_string(ciphertext_bits)

def des_decrypt(ciphertext, key):


"""Decrypts ciphertext using DES."""
ciphertext_bits = string_to_bits(ciphertext)
key_bits = string_to_bits(key)
key_bits = key_bits[:64]
if len(key_bits) < 64:
key_bits.extend([0] * (64 - len(key_bits)))

plaintext_bits = []
for i in range(0, len(ciphertext_bits), 64):
block = ciphertext_bits[i:i + 64]
plaintext_bits.extend(des(block, key_bits, decrypt=True))

padding_count = 0
for i in range(len(plaintext_bits)-1,0,-1):
if plaintext_bits[i] == 0:
padding_count+=1
else:
break
if padding_count > 0:
plaintext_bits = plaintext_bits[:-padding_count]

return bits_to_string(plaintext_bits)

# Example usage
key = input("Enter the key: ")
plaintext = input("Enter the plain text: ")

ciphertext = des_encrypt(plaintext, key)


print("Ciphertext:", ciphertext)

decrypted_plaintext = des_decrypt(ciphertext, key)


print("Decrypted plaintext:", decrypted_plaintext)

Output:

Conclusion:
INFORMATION SECURITY (3164603) 230173146008

The Data Encryption Standard (DES) is a symmetric-key block cipher that was widely used for data
encryption. It operates on 64-bit blocks of data using a 56-bit key, applying a series of
transformations and permutations to encrypt and decrypt the data. DES was adopted as a federal
standard in the United States in 1977 but has since been largely replaced by more secure algorithms,
such as AES (Advanced Encryption Standard), due to vulnerabilities that were discovered over time.

Quiz:

1. DES works on _______ size of blocks ?


Ans. 64-bit size of blocks.

2. How many steps DES consists?


Ans. DES consists of 16 steps (or rounds) for encryption and decryption.

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

References used by the students:


https://www.tutorialspoint.com/cryptography/data_encryption_standard.htm
geeksforgeek.com

Rubric wise marks obtained:

Rubrics 1 2 3 4 5 Total
Marks

Experiment No: 5

To implement Simple AES encryption-decryption.


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.
INFORMATION SECURITY (3164603) 230173146008

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


Theory: AES is asymmetric 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.
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:
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
INFORMATION SECURITY (3164603) 230173146008

import java.util.Base64;

public class SimpleAES {


public static void main(String[] args) throws Exception {
String plainText = "HelloAESWorld";

// Generate AES Key


KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(128); // For 128-bit AES
SecretKey secretKey = keyGen.generateKey();

// Encrypt
Cipher aesCipher = Cipher.getInstance("AES");
aesCipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] cipherText = aesCipher.doFinal(plainText.getBytes());
System.out.println("Encrypted Text: " +
Base64.getEncoder().encodeToString(cipherText));

// Decrypt
aesCipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedText = aesCipher.doFinal(cipherText);
System.out.println("Decrypted Text: " + new String(decryptedText));
}
}

Output:

Conclusion:
 Successfully understood and implemented the AES encryption and decryption process.
 AES ensures confidentiality by using secure symmetric encryption, making it suitable for
protecting sensitive data.
INFORMATION SECURITY (3164603) 230173146008

Quiz:

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

Answer: AES-192 performs 12 rounds.

Suggested Reference:
1. https://www.geeksforgeeks.org/advanced-encryption-standard-aes/
References used by the students:
https://www.geeksforgeeks.org/advanced-encryption-standard-aes/
javaTpoint.com

Rubric wise marks obtained:

Rubrics 1 2 3 4 5 Total
Marks
INFORMATION SECURITY (3164603) 230173146008

Experiment No: 6

To implement Simple RSA encryption-decryption.


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 ofRSA 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 integers:
(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:

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 ciphers * mod n.
INFORMATION SECURITY (3164603) 230173146008

Program:
from time import time

def gcd(a, b):


while b:
a, b = b, a % b
return a

def multiplicative_inverse(e, phi):


"""Compute the multiplicative inverse of e modulo phi"""

def extended_gcd(a, b):


if a == 0:
return b, 0, 1
else:
gcd, x, y = extended_gcd(b % a, a)
return gcd, y - (b // a) * x, x

gcd, x, y = extended_gcd(e, phi)


if gcd != 1:
return None
else:
return x % phi

def is_prime(num):
if num < 2:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True

def generate_keypair(p, q):


"""Generate a public and private key pair for RSA"""
if not (is_prime(p) and is_prime(q)):
raise ValueError('Both numbers must be prime.')
elif p == q:
raise ValueError('p and q cannot be equal')

# Step 1: Compute n
n=p*q

# Step 2: Compute phi (Euler's totient function)


phi = (p-1) * (q-1)

# Step 3: Choose an integer e such that e and phi(n) are coprime; 1 < e < phi
e=0
for i in range(2, phi):
if gcd(i, phi) == 1:
e=i
break

# Step 4:
d = multiplicative_inverse(e, phi)

# Public key is (e, n) and private key is (d, n)


return (e, n), (d, n)
INFORMATION SECURITY (3164603) 230173146008

def encrypt(pk, plaintext):


"""Encrypt a message using the public key"""
# Unpack the key into it's components
e, n = pk
# Convert each letter in the plaintext to numbers based on the character using a^b % m
cipher = [pow(ord(char), e, n) for char in plaintext]
return cipher

def decrypt(pk, ciphertext):


"""Decrypt a message using the private key"""
# Unpack the key into its components
d, n = pk
# Generate the plaintext based on the ciphertext and key using a^b mod m
plain = [chr(pow(char, d, n)) for char in ciphertext]
return ''.join(plain)

# Generate public and private keys


p = int(input("Enter first prime number(p): "))
q = int(input("Enter second prime number(q): "))
message = input("\nEnter plain text: ")

print("*"*60, "\nPlain text:", message)


startTime = time()
public, private = generate_keypair(p, q)
print("Public key:", public)
print("Private key:", private)

# Encrypt the message


encrypted_msg = encrypt(public, message)
print("Encrypted message:", encrypted_msg)

# Decrypt the message


decrypted_msg = decrypt(private, encrypted_msg)
print("Decrypted message:", decrypted_msg)

endTime = time()
print(f"Time taken to complete: {(endTime - startTime):.4f} seconds\n", "*"*60, sep="")

Output:
INFORMATION SECURITY (3164603) 230173146008

Conclusion: The RSA algorithm is a widely used public-key encryption algorithm that enables
secure data transmission by using a pair of keys: a public key for encryption and a private key for
decryption. It relies on the mathematical difficulty of factoring large composite numbers, making it a
secure method for protecting sensitive information.

Quiz:
1. if p=7, q=1 and e=13 than what will be value of d?
Here q = 1, but 1 is not a prime number. So the algorithm can’t be applied.

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

References used by the students:


Geeksforgeek.com
https://www.cemc.uwaterloo.ca/resources/real-world/RSA.pdf
javaTpoint.com

Rubric wise marks obtained:

Rubrics 1 2 3 4 5 Total
Marks
INFORMATION SECURITY (3164603) 230173146008

Experiment No: 7

Implement the Diffie-Hellman Key Exchange Method.


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 B and sends
the same back to Alice.
STEP-6: Now both of them compute their common secret key as the other one’s secret key
power of a mod p.
Program:
def powMod(base, expo, m):
result = 1
while expo > 0:
INFORMATION SECURITY (3164603) 230173146008

if expo % 2 == 1:
result = (result * base) % m
base = (base * base) % m
expo //= 2
return result

q = int(input("Enter q: "))
alp = int(input("Enter alpha: "))

Xa = int(input("Enter User A's private key(Xa): "))


Xb = int(input("Enter User B's private key(Xb): "))

Ya = powMod(alp, Xa, q)
Yb = powMod(alp, Xb, q)
print("User A's public key(Ya): ", Ya)
print("User B's public key(Yb): ", Yb)

k1 = powMod(Ya, Xb, q)
k2 = powMod(Yb, Xa, q)

print(f"The common secret key: k1 = {k1}, k2 = {k2}")

Output:

Conclusion: The Diffie-Hellman key exchange is a cryptographic method that allows two parties to
establish a shared secret key over an insecure communication channel. It works by each party
generating a pair of keys (public and private) and exchanging the public keys, which are then used to
calculate the shared secret key. This method ensures secure key exchange without actually
exchanging the secret key itself.

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 ?
Here, q=7, a=3, Xa=2, Xb=5.
Then, Ya=a^(Xa) % q = 3^(2)%7 = 2 and
Yb=a^(Xb) % q = 3^(5)%7 = 5
So, D-H key is Ya^(Xb) % q = 2^(5) % 7 = 4; Yb^(Xa) % q = 5^(2) % 7 = 4.

Suggested Reference:
1. https://www.techtarget.com/searchsecurity/definition/Diffie-Hellman-key-exchange
References used by the students:
https://www.techtarget.com/searchsecurity/definition/Diffie-Hellman-key-exchange

Rubric wise marks obtained:


INFORMATION SECURITY (3164603) 230173146008

Rubrics 1 2 3 4 5 Total
Marks

Experiment No: 8

Write a program to generate MD5 hash.


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 ofMD5 techniques.
Equipment/Instruments: Computer System, Turbo-c/ JDK
b
Theory: MD5processesavariale-length messageinto fixed-length output 128bits.The
inputmessageisbrokenupintochunksof512-bitblocks.Themessageispadedsothatitsd
e
lengthisdivisibleby512.Thepaddingworksasfollows:firstasinglebit,1,isappendedtothe
endofthemessage. This is followed by as many zeros as arerequired to bring the
lengthofthemessageupto64bitslessthanamultipleof512.Theremainingbitsarefilledupwith64bitsre
presentingthelengthoftheoriginalmessage,modulo264.Themainoperatesona128-
bitstate,dividedintofour32-
bitwords,denotedA,B,C,andD.Theseareinitializedtocertainfixedconstants.Themainalgorithmthen
useseach512-bitmessageblockinturntomodifythestat..

Example:
INFORMATION SECURITY (3164603) 230173146008

Algorithm:

STEP-1:Readthe128-bitplaintext.
STEP-2:Divideintofourblocksof32-bitsnamedasA,B,CandD.

STEP-3:Computethefunctionsf,g,handiwithoperationssuchas,rotations,permutations,etc,.
STEP-
4:TheoutputofthesefunctionsarecombinedtogetherasFandperformedcircularshi
ftingandthengiventokeyround.

STEP-5:Finally,rightshiftof‘s’timesareperformedandtheresultsarecombinedtogether
toproducethefinaloutput.

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

public class MD5HashGenerator {


public static void main(String[] args) {
try {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the message: ");
String input = sc.nextLine();

// Create MD5 Hash Instance


MessageDigest md = MessageDigest.getInstance("MD5");

// Update the message digest


md.update(input.getBytes());

// Complete the hash computation


byte[] digest = md.digest();

// Convert to Hexadecimal String


StringBuilder hexString = new StringBuilder();
for (byte b : digest) {
hexString.append(String.format("%02x", b & 0xff));
}

System.out.println("MD5 Hash: " + hexString.toString());


INFORMATION SECURITY (3164603) 230173146008

} catch (NoSuchAlgorithmException e) {
System.out.println("Exception: " + e.getMessage());
}
}
}

Output:

Conclusion:
 Successfully understood and implemented the working of the MD5 hashing algorithm.
 MD5 helps in ensuring message integrity by generating a unique 128-bit hash value.

Quiz:

1. MD5produce hash value of ____ bits?

Answer: 128 bits.

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
INFORMATION SECURITY (3164603) 230173146008

Experiment No: 9
Write a program to generate SHA-1 hash.
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 ofSHA-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 way this algorithm
works is that for a message of size < 264 bits it computes a 160-bit condensed output called
messagedigest.The SHA-1algorithm isdesignedsothatitis 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.Itissupposedtobe Unique Non-reversible.
Example:

Algorithm:
STEP-1:Readthe256-bitkeyvalues.
STEP-2:Divideintofiveequal-sizedblocksnamedA,B,C,DandE.
STEP-3:TheblocksB,CandDarepassedtothefunctionF.
STEP-4:TheresultantvalueispermutedwithblockE.
STEP-5:TheblockAisshiftedrightby‘s’timesandpermutedwiththeresultofstep-4.

STEP-6:
Thenitispermutedwithaweightvalueandthenwithsomeotherkeypairandtakenasthe
firstblock.
STEP-7:BlockAistakenasthesecondblockandtheblockBisshiftedby‘s’times and taken as the
third block.

STEP-8:TheblocksCandDaretakenastheblockDandEforthefinaloutput.
INFORMATION SECURITY (3164603) 230173146008

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

public class SHA1HashGenerator {


public static void main(String[] args) {
try {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the message: ");
String input = sc.nextLine();

// Create SHA-1 Hash Instance


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

// Update the message digest


md.update(input.getBytes());

// Complete the hash computation


byte[] digest = md.digest();

// Convert to Hexadecimal String


StringBuilder hexString = new StringBuilder();
for (byte b : digest) {
hexString.append(String.format("%02x", b & 0xff));
}

System.out.println("SHA-1 Hash: " + hexString.toString());


} catch (NoSuchAlgorithmException e) {
System.out.println("Exception: " + e.getMessage());
}
}
}

Output:

Conclusion:

 Successfully understood and implemented the SHA-1 hashing algorithm.


 SHA-1 generates a unique, fixed-size hash which verifies the integrity and authenticity of a
given message.

Quiz:

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

● Answer: 64 rounds.
INFORMATION SECURITY (3164603) 230173146008

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

● Answer: 160 bits.

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
INFORMATION SECURITY (3164603) 230173146008

Experiment No: 10

Implement a digital signature algorithm.


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.

Program:
import java.security.*;
import java.util.Base64;
import java.util.Scanner;

public class DigitalSignatureDemo {


public static void main(String[] args) {
try {
Scanner sc = new Scanner(System.in);
INFORMATION SECURITY (3164603) 230173146008

System.out.print("Enter the message to sign: ");


String message = sc.nextLine();

// Generate key pair


KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
keyGen.initialize(1024); // Key size
KeyPair pair = keyGen.generateKeyPair();
PrivateKey privateKey = pair.getPrivate();
PublicKey publicKey = pair.getPublic();

// Create a Signature object


Signature sign = Signature.getInstance("SHA1withDSA");
sign.initSign(privateKey);

// Add data to the signature


sign.update(message.getBytes());

// Sign the data


byte[] signatureBytes = sign.sign();
System.out.println("Digital Signature (Base64 Encoded): " +
Base64.getEncoder().encodeToString(signatureBytes));

// Now Verify the signature


Signature verifySign = Signature.getInstance("SHA1withDSA");
verifySign.initVerify(publicKey);
verifySign.update(message.getBytes());

boolean isVerified = verifySign.verify(signatureBytes);


System.out.println("Signature verification result: " + (isVerified ? "Valid Signature" :
"Invalid Signature"));

} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
}
}

Output:

Conclusion:
 Successfully implemented the Digital Signature Standard (DSS) using Java.
 Understood how digital signatures verify message integrity and authenticate the sender
INFORMATION SECURITY (3164603) 230173146008

without using encryption.

Quiz:

1. How many sub-algorithms does digital signature consist of?

● Answer: Three sub-algorithms:


1. Key Generation
2. Signature Generation
3. Signature Verification

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

References used by the students:


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

Rubric wise marks obtained:

Rubrics 1 2 3 4 5 Total
Marks
INFORMATION SECURITY (3164603) 230173146008

Tools and Case Studies


1. Study Cryptography and cryptanalysis concepts using CrypTool.
Date:
Objectives: (a) to understand the working fundamentals of CrypTool
Equipment/Instruments: Computer System, CrypTool.
Introduction:
The CrypTool installation is simple: download and extract the ziparchive, 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


INFORMATION SECURITY (3164603) 230173146008

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.

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.
INFORMATION SECURITY (3164603) 230173146008

Conclusion:
● CrypTool provides a hands-on approach to understand classical
cryptographic methods.
● The demonstration with Caesar Cipher explained how symmetric key
encryption and decryption work.
● It also shows the importance of a shared key (secret) in symmetric
cryptography.
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/
INFORMATION SECURITY (3164603) 230173146008

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

List of 10 Recent Cyber Attacks (2023-2024):


N Cyber Attack / Data Ye
Organization/Entity
o. Breach ar
Multiple Organizations 20
1 MOVEit Data Breach
(Progress Software) 23
MGM Resorts MGM Resorts 20
2
Cyberattack International 23
23andMe (DNA testing 20
3 23andMe Data Breach
company) 23
20
4 T-Mobile Data Breach T-Mobile US
23
Duolingo Scraped Data 20
5 Duolingo
Leak 23
Okta Support System 20
6 Okta
Breach 23
20
7 Discord.io Data Breach Discord.io
23
Latitude Financial Latitude Financial Services 20
8
Cyberattack (Australia) 23
Indian Council of Medical 20
9 ICMR (India)
Research (ICMR) Breach 23
1 Capita Ransomware 20
Capita (UK)
0 Attack 23

Detailed Explanation of One Case:

Case: MGM Resorts Cyberattack (2023)

● What Happened:

In September 2023, MGM Resorts International faced a major cyberattack that paralyzed its
systems. Hackers used social engineering tactics to gain access to internal systems.

● Method Used:


o The attack started with a social engineering phone call to the IT help desk.
o After gaining initial access, attackers deployed ransomware, encrypted files, and stole
sensitive customer data.
● Impact:
INFORMATION SECURITY (3164603) 230173146008

o Hotel bookings, casino operations, digital room keys, ATMs, and slot machines were
affected.
o Financial losses were estimated in the range of $100 million+.
o Customer personal details (such as names, addresses, and IDs) were compromised.

● Lessons Learned:

o Employee training against social engineering is critical.


o Backup systems must be regularly tested.
o Immediate containment protocols should be in place to isolate affected systems.

You might also like