0% found this document useful (0 votes)
69 views41 pages

INS Lab Manual Kush

Uploaded by

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

INS Lab Manual Kush

Uploaded by

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

FACULTY OF ENGINEERING AND TECHNOLOGY

BACHELOR OF TECHNOLOGY

INFORMATION AND NETWORK SECURITY


(203105311)

VII SEMESTER
COMPUTER SCIENCE & ENGINEERING DEPARTMENT

LABORATORY MANUAL
CERTIFICATE

This is to certify that with enrollment no.

has successfully completed /hisher laboratory


experiments in

INFORMATION AND NETWORK SECURITY LABORATORY (203105311)

From the department of Computer Science and Engineering during the

academic year 2024 – 2025.

Date of Submission :…………………………… Staff In Charge : ………………..……………

Head of Department : ……………………….


TABLE OF CONTENT

SR.NO PRACTICAL LIST PAGE PAGE START END MARKS SIGN.


NO. NO. DATE DATE
Implement Caesar
1. cipher encryption-
decryption.
Implement
2. Monoalphabetic cipher
encryption-decryption.
Implement Playfair
3. cipher encryption-
decryption.

Implement Hill cipher


4. encryption-decryption.

Implement
5. Polyalphabetic cipher
encryption-decryption.

Implement Simple
6. Transposition
encryption-decryption.
Implement Diffie-
7. Hellman Key exchange
Method

Implement One time


8. pad encryption-
decryption
Implement RSA
9. encryption-decryption
algorithm.
Demonstrate working
10. of Digital Signature
using Cryptool.
FACULTY OF ENGINEERING & TECHNOLOGY
Subject : Information & Network Security Laboratory
Subject Code: 203105311
B.Tech – 4th Year 7th Semester

Practical – 1

Aim:- A) Caesar Cipher EncryptionEncryption:

Theory:
• Caesar cipher is a substitution cipher where each letter in the plaintext is
shifted a certain number of places down or up the alphabet.
• It's a simple and historical method of encryption, but it's not very secure
due to its vulnerability to brute force attacks.
• The key idea is shifting letters by a fixed amount to encode and decode
messages.
• For Caesar cipher encryption, each letter in the plaintext is shifted a fixed
number of places down or up the alphabet.
• Let's say we have a shift of 3. So, 'A' becomes 'D', 'B' becomes 'E', and so
on.
• To decrypt, you simply shift back by the same number of places.
• It's a straightforward method but not very secure.
• The key is crucial for both encryption and decryption.

Code :-

def encrypt_message(plain_text, shift):


encrypted = []
for char in plain_text:
if char.isalpha():
# Handle uppercase letters
if char.isupper():
start = ord('A')
# Handle lowercase letters
else:
start = ord('a')
# Encrypt the character
m = (ord(char) - start + shift) % 26 + start
encrypted.append(chr(m))
1|Page
210303105509
FACULTY OF ENGINEERING & TECHNOLOGY
Subject : Information & Network Security Laboratory
Subject Code: 203105311
B.Tech – 4th Year 7th Semester

else:
# If the character is not a letter, do not change it
encrypted.append(char)
return ''.join(encrypted)

plain_text = input("Enter your message to encrypt: ")


shift = 3
encrypted_text = encrypt_message(plain_text, shift)
print("Encrypted message is:", encrypted_text)
plane_text = input("enter your text message to encrypt:")
encrypt = []
for i in plane_text:
encrypt.append(chr ((ord(i)+3)))
print("encrypted msg is : ",encrypt)

Output:-

2|Page
210303105509
FACULTY OF ENGINEERING & TECHNOLOGY
Subject : Information & Network Security Laboratory
Subject Code: 203105311
B.Tech – 4th Year 7th Semester

Aim:- B) Caesar Cipher Decryption

Code:-

def decrypt_message(encrypted_text, shift):


decrypted = []
for char in encrypted_text:
if char.isalpha():
# Handle uppercase letters
if char.isupper():
start = ord('A')
# Handle lowercase letters
else:
start = ord('a')
# Decrypt the character
n = (ord(char) - start - shift) % 26 + start
decrypted.append(chr(n))
else:
# If the character is not a letter, do not change it
decrypted.append(char)
return ''.join(decrypted)
encrypted_text = input("Enter your encrypted message to decrypt: ")
shift = 3
decrypted_text = decrypt_message(encrypted_text, shift)
print("Decrypted message is:", decrypted_text)

Output:-

3|Page
210303105509
FACULTY OF ENGINEERING & TECHNOLOGY
Subject : Information & Network Security Laboratory
Subject Code: 203105311
B.Tech – 4th Year 7th Semester

Practical – 2

Aim:- A) Monoalphabetic Cipher

Theory:
• A monoalphabetic cipher is a substitution cipher where each letter in the
plaintext is replaced by a corresponding letter from a fixed substitution
alphabet.
• This method ensures that each letter consistently maps to the same
substitute letter throughout the message.
• Although simple to implement, monoalphabetic ciphers are highly
vulnerable to frequency analysis, as the patterns in letter frequency
remain unchanged from the plaintext to the ciphertext.
• Historical examples, like the Caesar cipher, demonstrate the fundamental
concept of monoalphabetic encryption and its straightforward yet easily
breakable nature.

Code:

def generate_monoalphabetic_cipher():
mp = {}
j = 25
for i in range(26):
mp[chr(ord('a') + i)] = chr(ord('a') + j)
j -= 1
return mp

def encrypt_message(plain_text, cipher):


encrypted = []
for char in plain_text:
if char in cipher:
encrypted.append(cipher[char])
else:
encrypted.append(char)
4|Page
210303105509
FACULTY OF ENGINEERING & TECHNOLOGY
Subject : Information & Network Security Laboratory
Subject Code: 203105311
B.Tech – 4th Year 7th Semester

return ''.join(encrypted)

def decrypt_message(encrypted_text, cipher):


reversed_cipher = {v: k for k, v in cipher.items()}
decrypted = []
for char in encrypted_text:
if char in reversed_cipher:
decrypted.append(reversed_cipher[char])
else:
decrypted.append(char)
return ''.join(decrypted)

# Generate the cipher


cipher = generate_monoalphabetic_cipher()

# Input plain text


plain_text = input("Enter plain text: ").strip().lower()

# Encrypt the plain text


encrypted_text = encrypt_message(plain_text, cipher)
print("Encrypted:", encrypted_text)

# Decrypt the encrypted text


decrypted_text = decrypt_message(encrypted_text, cipher)
print("Decrypted:", decrypted_text)

Output:

5|Page
210303105509
FACULTY OF ENGINEERING & TECHNOLOGY
Subject : Information & Network Security Laboratory
Subject Code: 203105311
B.Tech – 4th Year 7th Semester

Practical – 3

Aim : A) Playfair Cipher Encryption

Theory:

• The Playfair cipher was the first practical digraph substitution cipher.
• In playfair cipher unlike traditional cipher we encrypt a pair of
alphabets(digraphs) instead of a single alphabet.
• Pair cannot be made with same letter.
• Break the letter in single and add a bogus letter to the previous letter.
• If the letter is standing alone in the process of pairing, then add an
extrabogus letter with the alone letter.
• If both the letters are in the same column: Take the letter below
eachone (going back to the top if at the bottom).

Code:

def to_lower_case(text):
return text.lower()

def remove_spaces(text):
return text.replace(" ", "")

def generate_key_table(key):
key = to_lower_case(remove_spaces(key)).replace('j', 'i')
dicty = [0] * 26
key_table = [[""] * 5 for _ in range(5)]
i, j = 0, 0

for k in key:
if k != 'j' and not dicty[ord(k) - ord('a')]:
dicty[ord(k) - ord('a')] = 1
key_table[i][j] = k
j += 1
6|Page
210303105509
FACULTY OF ENGINEERING & TECHNOLOGY
Subject : Information & Network Security Laboratory
Subject Code: 203105311
B.Tech – 4th Year 7th Semester

if j == 5:
i += 1
j=0

for k in range(26):
if k != 9 and not dicty[k]:
key_table[i][j] = chr(k + ord('a'))
j += 1
if j == 5:
i += 1
j=0

return key_table

def format_message(message):
message = to_lower_case(remove_spaces(message)).replace('j', 'i')
formatted_message = ""
i=0

while i < len(message):


if i + 1 < len(message) and message[i] == message[i + 1]:
formatted_message += message[i] + 'x'
i += 1
else:
formatted_message += message[i]
if i + 1 < len(message):
formatted_message += message[i + 1]
i += 2

if len(formatted_message) % 2 != 0:
formatted_message += 'x'

return formatted_message

7|Page
210303105509
FACULTY OF ENGINEERING & TECHNOLOGY
Subject : Information & Network Security Laboratory
Subject Code: 203105311
B.Tech – 4th Year 7th Semester

def find_position(char, key_table):


for row in range(5):
for col in range(5):
if key_table[row][col] == char:
return row, col

def playfair_encrypt(message, key):


key_table = generate_key_table(key)
message = format_message(message)
encrypted_message = ""

for i in range(0, len(message), 2):


row1, col1 = find_position(message[i], key_table)
row2, col2 = find_position(message[i + 1], key_table)

if row1 == row2:
encrypted_message += key_table[row1][(col1 + 1) % 5] +
key_table[row2][(col2 + 1) % 5]
elif col1 == col2:
encrypted_message += key_table[(row1 + 1) % 5][col1] + key_table[(row2
+ 1) % 5][col2]
else:
encrypted_message += key_table[row1][col2] + key_table[row2][col1]

return encrypted_message

key = "Keyword"
message = "Hello World"
encrypted_message = playfair_encrypt(message, key)

print(f"Key text: {key}")


print(f"Plain text: {message}")
print(f"Cipher text: {encrypted_message}")

8|Page
210303105509
FACULTY OF ENGINEERING & TECHNOLOGY
Subject : Information & Network Security Laboratory
Subject Code: 203105311
B.Tech – 4th Year 7th Semester

Output:

9|Page
210303105509
FACULTY OF ENGINEERING & TECHNOLOGY
Subject : Information & Network Security Laboratory
Subject Code: 203105311
B.Tech – 4th Year 7th Semester

Decryption Code:-

def to_lower_case(text):
return text.lower()

def remove_spaces(text):
return text.replace(" ", "")

def generate_key_table(key):
key = to_lower_case(remove_spaces(key)).replace('j', 'i')
dicty = [0] * 26
key_table = [[""] * 5 for _ in range(5)]
i, j = 0, 0

for k in key:
if k != 'j' and not dicty[ord(k) - ord('a')]:
dicty[ord(k) - ord('a')] = 1
key_table[i][j] = k
j += 1
if j == 5:
i += 1
j=0

for k in range(26):
if k != 9 and not dicty[k]:
key_table[i][j] = chr(k + ord('a'))
j += 1
if j == 5:
i += 1
j=0

return key_table

def format_message(message):
message = to_lower_case(remove_spaces(message)).replace('j', 'i')
formatted_message = ""
i=0

10 | P a g
210303105509
FACULTY OF ENGINEERING & TECHNOLOGY
Subject : Information & Network Security Laboratory
Subject Code: 203105311
B.Tech – 4th Year 7th Semester

while i < len(message):


if i + 1 < len(message) and message[i] == message[i + 1]:
formatted_message += message[i] + 'x'
i += 1
else:
formatted_message += message[i]
if i + 1 < len(message):
formatted_message += message[i + 1]
i += 2

if len(formatted_message) % 2 != 0:
formatted_message += 'x'

return formatted_message

def find_position(char, key_table):


for row in range(5):
for col in range(5):
if key_table[row][col] == char:
return row, col

def playfair_encrypt(message, key):


key_table = generate_key_table(key)
message = format_message(message)
encrypted_message = ""

for i in range(0, len(message), 2):


row1, col1 = find_position(message[i], key_table)
row2, col2 = find_position(message[i + 1], key_table)

if row1 == row2:
encrypted_message += key_table[row1][(col1 + 1) % 5] +
key_table[row2][(col2 + 1) % 5]
elif col1 == col2:
encrypted_message += key_table[(row1 + 1) % 5][col1] + key_table[(row2
+ 1) % 5][col2]
else:
encrypted_message += key_table[row1][col2] + key_table[row2][col1]
11 | P a g
210303105509
FACULTY OF ENGINEERING & TECHNOLOGY
Subject : Information & Network Security Laboratory
Subject Code: 203105311
B.Tech – 4th Year 7th Semester

return encrypted_message

def playfair_decrypt(encrypted_message, key):


key_table = generate_key_table(key)
decrypted_message = ""

for i in range(0, len(encrypted_message), 2):


row1, col1 = find_position(encrypted_message[i], key_table)
row2, col2 = find_position(encrypted_message[i + 1], key_table)

if row1 == row2:
decrypted_message += key_table[row1][(col1 - 1) % 5] +
key_table[row2][(col2 - 1) % 5]
elif col1 == col2:
decrypted_message += key_table[(row1 - 1) % 5][col1] + key_table[(row2 -
1) % 5][col2]
else:
decrypted_message += key_table[row1][col2] + key_table[row2][col1]

return decrypted_message

key = "Keyword"
message = "Hello World"
encrypted_message = playfair_encrypt(message, key)
decrypted_message = playfair_decrypt(encrypted_message, key)

print(f"Key text: {key}")


print(f"Plain text: {message}")
print(f"Cipher text: {encrypted_message}")
print(f"Decrypted text: {decrypted_message}")

Output:-

12 | P a g
210303105509
FACULTY OF ENGINEERING & TECHNOLOGY
Subject : Information & Network Security Laboratory
Subject Code: 203105311
B.Tech – 4th Year 7th Semester

13 | P a g
210303105509
FACULTY OF ENGINEERING & TECHNOLOGY
Subject : Information & Network Security Laboratory
Subject Code: 203105311
B.Tech – 4th Year 7th Semester

Practical – 4
Aim :- A) Hill Cipher Encryption

Theory:
• Hill cipher is a polygraphic substitution cipher based on linear algebra.
• Each letter is represented by a number modulo 26.
• To encrypt a message, each block of n letters (considered as an n-
component vector) is multiplied by an invertible n × n matrix,
againstmodulus 26.
• To decrypt the message, each block is multiplied by the inverse of
thematrix used for encryption.
• The matrix used for encryption is the cipher key, and it should be
chosenrandomly from the set of invertible n × n matrices (modulo 26).

Code:

def to_lower_case(text):
return text.lower()

def remove_spaces(text):
return text.replace(" ", "")

def create_matrix_of_integers_from_string(string, m):


integers = [ord(char) - ord('a') for char in string]
matrix = []
for i in range(0, len(integers), m):
matrix.append(integers[i:i + m])
return matrix

def create_string_from_matrix(matrix):
string = ''.join(chr(num % 26 + ord('a')) for row in matrix for num in row)
return string

def matrix_multiply(A, B):


result = [[0] * len(B[0]) for _ in range(len(A))]
for i in range(len(A)):
for j in range(len(B[0])):
14 | P a g
210303105509
FACULTY OF ENGINEERING & TECHNOLOGY
Subject : Information & Network Security Laboratory
Subject Code: 203105311
B.Tech – 4th Year 7th Semester

for k in range(len(B)):
result[i][j] += A[i][k] * B[k][j]
result[i][j] %= 26
return result

def encrypt_message(message, key_matrix):


m = len(key_matrix)
message_matrix = create_matrix_of_integers_from_string(message, m)
encrypted_matrix = matrix_multiply(key_matrix, message_matrix)
encrypted_message = create_string_from_matrix(encrypted_matrix)
return encrypted_message

key = "GYBNQKURP"
key_size = 3

key_matrix = create_matrix_of_integers_from_string(key, key_size)

message = "ACT"
message = to_lower_case(remove_spaces(message))

encrypted_message = encrypt_message(message, key_matrix)

print(f"Key text: {key}")


print(f"Plain text: {message}")
print(f"Cipher text: {encrypted_message}")

Output:

15 | P a g
210303105509
FACULTY OF ENGINEERING & TECHNOLOGY
Subject : Information & Network Security Laboratory
Subject Code: 203105311
B.Tech – 4th Year 7th Semester

B) Hill Cipher Decryption:-

def to_lower_case(text):
return text.lower()

def remove_spaces(text):
return text.replace(" ", "")

def create_matrix_of_integers_from_string(string, m):


integers = [ord(char) - ord('a') for char in string]
matrix = []
for i in range(0, len(integers), m):
matrix.append(integers[i:i + m])
return matrix

def create_string_from_matrix(matrix):
string = ''.join(chr(num % 26 + ord('a')) for row in matrix for num in row)
return string

def matrix_multiply(A, B):


result = [[0] * len(B[0]) for _ in range(len(A))]
for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(B)):
result[i][j] += A[i][k] * B[k][j]
result[i][j] %= 26
return result

def matrix_inverse(key_matrix):

determinant = key_matrix[0][0] * (key_matrix[1][1] * key_matrix[2][2] -


key_matrix[1][2] * key_matrix[2][1]) \
16 | P a g
210303105509
FACULTY OF ENGINEERING & TECHNOLOGY
Subject : Information & Network Security Laboratory
Subject Code: 203105311
B.Tech – 4th Year 7th Semester

- key_matrix[0][1] * (key_matrix[1][0] * key_matrix[2][2] -


key_matrix[1][2] * key_matrix[2][0]) \
+ key_matrix[0][2] * (key_matrix[1][0] * key_matrix[2][1] -
key_matrix[1][1] * key_matrix[2][0])

det_inv = pow(determinant, -1, 26) % 26

adjugate_matrix = [
[(key_matrix[1][1] * key_matrix[2][2] - key_matrix[1][2] * key_matrix[2][1]),
-(key_matrix[0][1] * key_matrix[2][2] - key_matrix[0][2] * key_matrix[2][1]),
(key_matrix[0][1] * key_matrix[1][2] - key_matrix[0][2] * key_matrix[1][1])],

[-(key_matrix[1][0] * key_matrix[2][2] - key_matrix[1][2] * key_matrix[2][0]),


(key_matrix[0][0] * key_matrix[2][2] - key_matrix[0][2] * key_matrix[2][0]),
-(key_matrix[0][0] * key_matrix[1][2] - key_matrix[0][2] * key_matrix[1][0])],

[(key_matrix[1][0] * key_matrix[2][1] - key_matrix[1][1] * key_matrix[2][0]),


-(key_matrix[0][0] * key_matrix[2][1] - key_matrix[0][1] * key_matrix[2][0]),
(key_matrix[0][0] * key_matrix[1][1] - key_matrix[0][1] * key_matrix[1][0])]
]

adjugate_matrix = [[elem % 26 for elem in row] for row in adjugate_matrix]

key_inverse = [[elem * det_inv % 26 for elem in row] for row in


adjugate_matrix]

return key_inverse

def decrypt_message(encrypted_message, key_matrix):


key_inverse = matrix_inverse(key_matrix)
decrypted_matrix = matrix_multiply(key_inverse,
17 | P a g
210303105509
FACULTY OF ENGINEERING & TECHNOLOGY
Subject : Information & Network Security Laboratory
Subject Code: 203105311
B.Tech – 4th Year 7th Semester

create_matrix_of_integers_from_string(encrypted_message, len(key_matrix)))
decrypted_message = create_string_from_matrix(decrypted_matrix)
return decrypted_message

key = "GYBNQKURP"
key_size = 3
key_matrix = create_matrix_of_integers_from_string(key, key_size)

message = "ACT"
message = to_lower_case(remove_spaces(message))

encrypted_message = create_string_from_matrix(matrix_multiply(key_matrix,
create_matrix_of_integers_from_string(message, key_size)))

decrypted_message = decrypt_message(encrypted_message, key_matrix)

print(f"Key text: {key}")


print(f"Plain text: {message}")
print(f"Cipher text: {encrypted_message}")
print(f"Decrypted text: {decrypted_message}")

OutPut:-

18 | P a g
210303105509
FACULTY OF COMPUTER SCIENCE ANDENGINEERING
INFORMATION AND NETWORK SECURITY LABORATORY
(203105311)
B.TECH CSE 7THSEMESTER 4THYEAR

PRACTICAL-5
AIM: Polyalphabetic Encryption and Decryption
CODE
def generate_key(string, key):

key = list(key)

if len(string) == len(key):

return(key)

else:

for i in range(len(string) - len(key)):

key.append(key[i % len(key)])

return("" . join(key))

def encrypt(string, key):

cipher_text = []

for i in range(len(string)):

x = (ord(string[i]) + ord(key[i])) % 26

x += ord('A')

cipher_text.append(chr(x))

return("" . join(cipher_text))

def decrypt(cipher_text, key):

orig_text = []

for i in range(len(cipher_text)):

x = (ord(cipher_text[i]) - ord(key[i]) + 26) % 26

x += ord('A')

orig_text.append(chr(x))

return("" . join(orig_text))

210303105509
FACULTY OF COMPUTER SCIENCE ANDENGINEERING
INFORMATION AND NETWORK SECURITY LABORATORY
(203105311)
B.TECH CSE 7THSEMESTER 4THYEAR
if name == " main ":

string = input("Enter the plaintext: ").upper()

keyword = input("Enter the keyword: ").upper()

key = generate_key(string, keyword)

cipher_text = encrypt(string, key)

print("Encrypted Text: ", cipher_text)

decrypted_text = decrypt(cipher_text, key)

print("Decrypted Text: ", decrypted_text)

output

210303105509
FACULTY OF COMPUTER SCIENCE ANDENGINEERING
INFORMATION AND NETWORK SECURITY LABORATORY
(203105311)
B.TECH CSE 7THSEMESTER 4THYEAR

PRACTICAL-6
AIM: Simple Transposition Encryption and Decryption.
CODE :
def generate_key(string, key):
key = list(key)
if len(string) == len(key):
return(key)
else:
for i in range(len(string) - len(key)):
key.append(key[i % len(key)])
return("" . join(key))
def encrypt(string, key):
cipher_text = []
for i in range(len(string)):
x = (ord(string[i]) + ord(key[i])) % 26
x += ord('A')
cipher_text.append(chr(x))
return("" . join(cipher_text))

def decrypt(cipher_text, key):


orig_text = []
for i in range(len(cipher_text)):
x = (ord(cipher_text[i]) - ord(key[i]) + 26) % 26
x += ord('A')

210303105509
FACULTY OF COMPUTER SCIENCE ANDENGINEERING
INFORMATION AND NETWORK SECURITY LABORATORY
(203105311)
B.TECH CSE 7THSEMESTER 4THYEAR

orig_text.append(chr(x))
return("" . join(orig_text))
if name == " main ":
string = input("Enter the plaintext: ").upper()
keyword = input("Enter the keyword: ").upper()

key = generate_key(string, keyword)


cipher_text = encrypt(string, key)
print("Encrypted Text: ", cipher_text)

decrypted_text = decrypt(cipher_text, key)


print("Decrypted Text: ", decrypted_text)

OUTPUT

210303105509
FACULTY OF COMPUTER SCIENCE ANDENGINEERING
INFORMATION AND NETWORK SECURITY LABORATORY
(203105311)
B.TECH CSE 7THSEMESTER 4THYEAR

PRACTICAL-7
AIM:-Diffie- Heilman key exchange method\
CODE;-

import random
def mod_exp(base, exp, mod):
result = 1
while exp > 0:
if exp % 2 == 1: # If exp is odd
result = (result * base) % mod
exp = exp // 2
base = (base * base) % mod
return result
def diffie_hellman(p, g):
a = random.randint(1, p-1)
A = mod_exp(g, a, p)
b = random.randint(1, p-1)
B = mod_exp(g, b, p)
alice_secret = mod_exp(B, a, p)
bob_secret = mod_exp(A, b, p)
return alice_secret, bob_secret
if name == " main "
p = int(input("Enter a large prime number (p): "))
g = int(input("Enter a base (g): "))

alice_secret, bob_secret = diffie_hellman(p, g)


print("Alice's Shared Secret: ", alice_secret)
print("Bob's Shared Secret: ", bob_secret)
if alice_secret == bob_secret:
print("Key exchange successful!")
else:
print("Key exchange failed!")

210303105509
FACULTY OF COMPUTER SCIENCE ANDENGINEERING
INFORMATION AND NETWORK SECURITY LABORATORY
(203105311)
B.TECH CSE 7THSEMESTER 4THYEAR

210303105509
Faculty of Engineering & Technology
Subject name & code : Information &
Network Security (203105311)
B.Tech CSE Year: 4th Sem : 7th

Practical - 8
AIM: Implement Diffie Hellman key exchange method.

Theory:

The Diffie-Hellman key exchange is a cryptographic protocol that allows two parties to securely
share a secret key over an insecure channel. It works by each party selecting a private key, then
generating and exchanging public keys based on a shared prime number and base. Both parties can
then independently compute the same shared secret using their own private key and the other
party's public key. The security of the protocol relies on the difficulty of solving the discrete
logarithm problem, making it secure even if the exchanged public keys are intercepted.

Key Concepts:

1. Public Parameters:
o Prime number p: A large prime number.
o Base g: A primitive root modulo p, typically a small integer.

Both p and g are public and can be known by everyone.

2. Private Keys:
o Alice’s private key a: A secret number randomly chosen by Alice.
o Bob’s private key b: A secret number randomly chosen by Bob.

These private keys are kept secret and are not shared with anyone.

3. Public Keys:
o Alice’s public key A: Calculated as A=ga mod p.
o Bob’s public key B: Calculated as B=gb mod p.

These public keys are shared between Alice and Bob.

Key Exchange Process:

1. Global Parameters:

▪ Both Alice and Bob agree on a common prime number p and a base g, where g is a
primitive root modulo p.

2. Select Private Keys:

▪ Alice selects a private key XA such that XA<p.


▪ Bob selects a private key XB such that XB<p.

210303105509 |
Faculty of Engineering & Technology
Subject name & code : Information &
Network Security (203105311)
B.Tech CSE Year: 4th Sem : 7th

3. Calculate Public Keys:

▪ Alice computes her public key YA using the formula YA= gXA mod p.

▪ Bob computes his public key YB using the formula YB=. gX Bmod p.

4. Exchange Public Keys:

▪ Alice and Bob share their public keys YA and YB with each other.

5. Calculate the Shared Secret Key:


▪ Alice computes the shared secret key K using Bob's public key YB and her private
key XA with the formula K = YB XAmod p.
▪ Bob computes the shared secret key K using Alice's public key YA and her
private key XB with the formula K = YAXBmod p.

Both Alice and Bob will arrive at the same shared secret key K, which can be used for secure
communication. The exchange process relies on the difficulty of calculating the discrete logarithm,
ensuring that the shared secret remains secure even if an eavesdropper knows the public keys.

210303105509 |
Faculty of Engineering & Technology
Subject name & code : Information &
Network Security (203105311)
B.Tech CSE Year: 4th Sem : 7th

Code:

def modular_pow(base, exponent, mod):


result = 1
base = base % mod
while exponent > 0:
if (exponent % 2) == 1:
result = (result * base) % mod
exponent = exponent >> 1
base = (base * base) % mod
return result

def diffie_hellman(p, g, a, b):


A = modular_pow(g, a, p)
B = modular_pow(g, b, p)

shared_secret_alice = modular_pow(B, a, p)
shared_secret_bob = modular_pow(A, b, p)

return A, B, shared_secret_alice, shared_secret_bob

if name == " main ":


p = int(input("Enter a prime number (p): "))
g = int(input("Enter a primitive root modulo p (g): "))
a = int(input("Enter Alice's private key (a): "))
b = int(input("Enter Bob's private key (b): "))

A, B, shared_secret_alice, shared_secret_bob = diffie_hellman(p, g, a, b)

print("\nDiffie-Hellman Key Exchange:")


print("Alice's public key (A):", A)
print("Bob's public key (B):", B)
print("Shared secret computed by Alice:", shared_secret_alice)
print("Shared secret computed by Bob:", shared_secret_bob)

if shared_secret_alice == shared_secret_bob:
print("\nSuccess! The shared secrets match.")
else:
print("\nError! The shared secrets do not match.")

210303105509 |
Faculty of Engineering & Technology
Subject name & code : Information &
Network Security (203105311)
B.Tech CSE Year: 4th Sem : 7th

Output:

Result:

The implementation of Diffie Hellman key exchange algorithm encryption and decryption has
been successfully completed.

210303105509 |
Faculty of Engineering & Technology
Subject name & code : Information &
Network Security (203105311)
B.Tech CSE Year: 4th Sem : 7th

Practical - 9
AIM: Implement RSA encryption-decryption algorithm.

Theory:

The RSA algorithm (Rivest-Shamir-Adleman) is one of the first public-key cryptosystems and is
widely used for secure data transmission. It is an asymmetric encryption algorithm, meaning it
uses two different keys: a public key for encryption and a private key for decryption.

Steps in RSA Algorithm:

1. Key Generation:
• Choose two large prime numbers, p and q.
• Compute n = p×q. This is used as part of both the public and private keys.
• Compute Euler's totient function ϕ(n)=(p−1)×(q−1).
• Choose an integer e such that 1<e<ϕ(n) and e is coprime with ϕ(n). This e becomes
the public key exponent.
• Compute d, the modular multiplicative inverse of e, such that d×e≡1(mod ϕ (n)).
This d becomes the private key exponent.
• Public Key: (n,e)
• Private Key: (n,d)

2. Encryption: To encrypt a message m (where m is a number such that 0≤m<n):


• Ciphertext ccc is calculated as: c = me mod n

3. Decryption: To decrypt the ciphertext c:


• The original message m is recovered using: m = cd mod n

210303105509 |
Faculty of Engineering & Technology
Subject name & code : Information &
Network Security (203105311)
B.Tech CSE Year: 4th Sem : 7th

Code:

import random

# Function to compute the greatest common divisor


def gcd(a, b):
while b != 0:
a, b = b, a % b
return a

# Function to find modular inverse using Extended Euclidean Algorithm


def modinv(a, m):
m0, x0, x1 = m, 0, 1
if m == 1:
return 0
while a > 1:
q = a // m
m, a = a % m, m
x0, x1 = x1 - q * x0, x0
if x1 < 0:
x1 += m0
return x1

# Function to generate RSA keys


def generate_keys():
# Function to check if a number is prime
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True

# Generate two large prime numbers, p and q


p=q=0
while not is_prime(p):
p = random.randint(50, 100) # Smaller primes for simplicity increase range for real
security
while not is_prime(q) or q == p:
q = random.randint(50, 100)

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

210303105509 |
Faculty of Engineering & Technology
Subject name & code : Information &
Network Security (203105311)
B.Tech CSE Year: 4th Sem : 7th

# Choose e such that 1 < e < phi and gcd(e, phi) = 1


e = random.randrange(2, phi)
while gcd(e, phi) != 1:
e = random.randrange(2, phi)

# Calculate d (modular inverse of e)


d = modinv(e, phi)

# Return public and private keys


return (n, e), (n, d)

# Function to encrypt a message


def encrypt(public_key, message):
n, e = public_key
message_int = [ord(char) for char in message] # Convert each character to its ASCII value
ciphertext = [(m ** e) % n for m in message_int]
return ciphertext

# Function to decrypt a message


def decrypt(private_key, ciphertext):
n, d = private_key
decrypted_message = [(c ** d) % n for c in ciphertext]
message = ''.join([chr(m) for m in decrypted_message]) # Convert ASCII values back
to characters
return message

# Main program
def main():
# Key generation
public_key, private_key = generate_keys()
print(f"Public Key: {public_key}")
print(f"Private Key: {private_key}")

# User input for message


message = input("Enter a message to encrypt: ")

# Encrypt the message


encrypted_message = encrypt(public_key, message)
print(f"Encrypted message: {encrypted_message}")
# Decrypt the message
decrypted_message = decrypt(private_key, encrypted_message)
print(f"Decrypted message: {decrypted_message}")

if name == " main ":


main()

210303105509 |
Faculty of Engineering & Technology
Subject name & code : Information &
Network Security (203105311)
B.Tech CSE Year: 4th Sem : 7th

Output:

Result:

The implementation of RSA algorithm encryption and decryption has been successfully
completed.

210303105509 |
Faculty of Engineering & Technology
Subject name & code : Information &
Network Security (203105311)
B.Tech CSE Year: 4th Sem : 7th

Practical - 10
AIM: Demonstrate working of Digital Signature using Cryptool.

Theory:

Digital Signature:

A digital signature in cryptography is a mechanism that ensures the authenticity, integrity, and non-
repudiation of digital messages or documents. It's similar to a handwritten signature or a stamped
seal but offers far more security. Digital signatures use asymmetric cryptography, which involves
a pair of keys: a private key and a public key.

Key Components of Digital Signatures:

1. Private Key: Used by the signer to create the signature. Only the owner of the private key
can sign the document.
2. Public Key: Used by others to verify the signature. Anyone with the public key can check
whether the document was signed by the corresponding private key.

Process:
1. Hashing: First, the document or message is hashed using a cryptographic hash function
(e.g., SHA-256). This creates a fixed-size output (hash) representing the document.
2. Signing: The hash of the document is then encrypted with the signer's private key. This
encrypted hash is the digital signature.
3. Verification:
o The receiver decrypts the signature using the sender's public key, obtaining the
original hash.
o The receiver also hashes the received document using the same hash function.
o If the decrypted hash matches the hash of the received document, the signature is
valid, confirming that the document hasn't been altered and was signed by the
legitimate private key owner.

CrypTool:

CrypTool is an open-source project that provides a suite of tools and educational resources for
learning and experimenting with cryptography. It is widely used by students, educators, and
cryptography enthusiasts to understand cryptographic concepts and algorithms through a hands-
on approach.

Key Features of CrypTool:


1. Cryptographic Algorithms: CrypTool supports a wide range of cryptographic algorithms,
including:
o Symmetric encryption: AES, DES, Blowfish, etc.

210303105509 |
Faculty of Engineering & Technology
Subject name & code : Information &
Network Security (203105311)
B.Tech CSE Year: 4th Sem : 7th

o Asymmetric encryption: RSA, ElGamal, ECC, etc.


o Hash functions: MD5, SHA family, etc.
o Digital signatures and certificates
o Key exchange protocols: Diffie-Hellman, etc.

2. Visual Representation: It provides visual demonstrations of how encryption, decryption,


and other cryptographic operations work. This is particularly helpful for understanding
complex algorithms and their inner workings.

3. Hands-on Exercises: Users can perform cryptographic tasks such as encryption,


decryption, key generation, digital signing, and verification. CrypTool enables you to
experiment with different algorithms, key sizes, and modes of operation.

4. CrypTool Variants: There are several versions of CrypTool, each designed for different
needs:
o CrypTool 1 (CT1): A desktop application focused on classical and modern
cryptography.
o CrypTool 2 (CT2): Provides a modern, flexible environment for experimenting
with cryptographic algorithms. It includes drag-and-drop functionality for visual
programming and workflows.
o JCrypTool (JCT): A Java-based version for cross-platform usage, with a focus on
modularity.
o CrypTool Online (CTO): A web-based version that allows users to experiment
with cryptography through their web browser without needing to install software.

5. Analysis Tools: CrypTool offers tools for analyzing cryptographic strengths, such as:
o Frequency analysis: For breaking classical ciphers (Caesar, Vigenère, etc.).
o Side-channel attack simulations
o Statistical tests on the randomness of cipher outputs.

6. Educational Tutorials: CrypTool provides step-by-step tutorials and explanations of


cryptographic concepts, making it an excellent resource for both beginners and advanced
learners.

Following are the steps involved in generating a digital signature using cryptool:

1. Launch CrypTool: Open CrypTool, a software that offers various cryptographic functions.

210303105509 |
Faculty of Engineering & Technology
Subject name & code : Information &
Network Security (203105311)
B.Tech CSE Year: 4th Sem : 7th

2. Load/Enter the Message: Input the message or file you want to sign. You can either type
the text manually or import a file.
3. Select Hash Function: Choose a hash function (e.g., SHA-256) to generate a fixed-size
hash (message digest) from the original message.

4. Choose Asymmetric Key Algorithm: Select a public-key cryptography algorithm like RSA
or DSAfor signing. You will need a private key for signing and a public key for verification.
5. Generate Key Pair: If you don’t already have a key pair, generate a new one (private and
public key). The private key will be used to create the digital signature.

210303105509 |
Faculty of Engineering & Technology
Subject name & code : Information &
Network Security (203105311)
B.Tech CSE Year: 4th Sem : 7th

210303105509 |
Faculty of Engineering & Technology
Subject name & code : Information &
Network Security (203105311)
B.Tech CSE Year: 4th Sem : 7th

210303105509 |
Faculty of Engineering & Technology
Subject name & code : Information &
Network Security (203105311)
B.Tech CSE Year: 4th Sem : 7th

6. Sign the Message: Using the private key, the message digest (from step 3) is encrypted,
producing the digital signature.
7. Save or Export: Save or export the digital signature along with the original message if
needed.
8. Verify the Signature (optional): Use the public key to verify the digital signature to ensure
the message hasn’t been tampered with.

These steps allow the sender to sign the message, ensuring authenticity and integrity.

210303105509 |

You might also like