IS

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

INFORMATION SECURITY (3170720) 191390107018

PRACTICAL 1
AIM : Implement Caesar cipher encryption-decryption.
CODE: def encrypt(text,s):
result = ""
for i in range(len(text)):
char = text[i]
if (char.isupper()):
result += chr((ord(char) + s-65) % 26 + 65)
else:
result += chr((ord(char) + s - 97) % 26 + 97)
return result
text = "ATTACKATONCE"
s=4
print("Text : " + text)
print("Shift : " + str(s))
print("Cipher: " + encrypt(text,s))

OUTPUT:

1
INFORMATION SECURITY (3170720) 191390107018

PRACTICAL 2
AIM: Implement Brute Force attack on Caesar cipher.
CODE:
def caesar_cipher_brute_force(ciphertext):
alphabet = "abcdefghijklmnopqrstuvwxyz"
ciphertext = ciphertext.lower()

print("Ciphertext: \"{}\"".format(ciphertext))
print("\nAttempting to decrypt using brute force:\n")

for shift in range(26):


plaintext = ""

for char in ciphertext:


if char in alphabet:
new_position = (alphabet.index(char) - shift) % 26
plaintext += alphabet[new_position]
else:
plaintext += char

print("Shift {}: \"{}\"".format(shift, plaintext))

2
INFORMATION SECURITY (3170720) 191390107018

if __name__ == "__main__":
encrypted_text = input("Enter the ciphertext to decrypt: ")
caesar_cipher_brute_force(encrypted_text)

OUTPUT:

3
INFORMATION SECURITY (3170720) 191390107018

4
INFORMATION SECURITY (3170720) 191390107018

PRACTICAL 3

AIM: Implement Monoalphabetic cipher encryption-decryption.


CODE:
import random

def generate_key():
alphabet = "abcdefghijklmnopqrstuvwxyz"
shuffled = list(alphabet)
random.shuffle(shuffled)
return dict(zip(alphabet, shuffled))

def monoalphabetic_encrypt(plaintext, key):


ciphertext = ""
for char in plaintext.lower():
if char in key:
ciphertext += key[char]
else:
ciphertext += char
return ciphertext

def monoalphabetic_decrypt(ciphertext, key):

5
INFORMATION SECURITY (3170720) 191390107018

reverse_key = {v: k for k, v in key.items()}


plaintext = ""
for char in ciphertext:
if char in reverse_key:
plaintext += reverse_key[char]
else:
plaintext += char
return plaintext

if __name__ == "__main__":
key = generate_key()
print("Generated Key:", key)

plaintext = input("Enter the plaintext to encrypt: ")

encrypted_text = monoalphabetic_encrypt(plaintext, key)


print("Encrypted Text:", encrypted_text)

decrypted_text = monoalphabetic_decrypt(encrypted_text, key)


print("Decrypted Text:", decrypted_text)

6
INFORMATION SECURITY (3170720) 191390107018

OUTPUT:
Generated Key: {'a': 'y', 'b': 'g', 'c': 't', 'd': 'u', 'e': 'r', 'f': 'c', 'g': 'z', 'h': 'a',
'i': 'b', 'j': 'k', 'k': 'm', 'l': 's', 'm': 'i', 'n': 'd', 'o': 'o', 'p': 'l', 'q': 'n', 'r': 'p', 's':
'f', 't': 'q', 'u': 'w', 'v': 'j', 'w': 'h', 'x': 'v', 'y': 'e', 'z': 'x'}
Enter the plaintext to encrypt: hello how are you
Encrypted Text: arsso aoh ypr eow
Decrypted Text: hello how are you

7
INFORMATION SECURITY (3170720) 191390107018

PRACTICAL 4
AIM: Implement Playfair cipher encryption-decryption.
CODE:
def generate_playfair_key(keyword):
alphabet = "abcdefghiklmnopqrstuvwxyz"
keyword = "".join(dict.fromkeys(keyword.lower().replace("j", "i")))
key_string = keyword + "".join([char for char in alphabet if char not in
keyword])
return [key_string[i:i + 5] for i in range(0, 25, 5)]

def preprocess_text(text):
text = text.lower().replace("j", "i").replace(" ", "")
digraphs = []
i=0
while i < len(text):
char1 = text[i]
if i + 1 < len(text) and text[i + 1] != char1:
char2 = text[i + 1]
i += 2
else:
char2 = "x" if char1 != "x" else "z"
i += 1

8
INFORMATION SECURITY (3170720) 191390107018

digraphs.append(char1 + char2)
return digraphs

def find_position(key_matrix, char):


for row_idx, row in enumerate(key_matrix):
if char in row:
return row_idx, row.index(char)

def playfair_encrypt_decrypt(digraphs, key_matrix, mode="encrypt"):


result = ""
shift = 1 if mode == "encrypt" else -1
for digraph in digraphs:
row1, col1 = find_position(key_matrix, digraph[0])
row2, col2 = find_position(key_matrix, digraph[1])

if row1 == row2:
result += key_matrix[row1][(col1 + shift) % 5] +
key_matrix[row2][(col2 + shift) % 5]
elif col1 == col2:
result += key_matrix[(row1 + shift) % 5][col1] + key_matrix[(row2
+ shift) % 5][col2]
else:
result += key_matrix[row1][col2] + key_matrix[row2][col1]
9
INFORMATION SECURITY (3170720) 191390107018

return result

if __name__ == "__main__":
keyword = input("Enter the keyword: ")
key_matrix = generate_playfair_key(keyword)

print("Generated Key Matrix:")


for row in key_matrix:
print(" ".join(row))

choice = input("Choose mode (encrypt/decrypt): ").strip().lower()


text = input("Enter the text: ")

digraphs = preprocess_text(text)
result = playfair_encrypt_decrypt(digraphs, key_matrix,
mode=choice)

print(f"Resulting text ({choice}):", result)

10
INFORMATION SECURITY (3170720) 191390107018

OUTPUT:

11
INFORMATION SECURITY (3170720) 191390107018

PRACTICAL 5
AIM: Implement Polyalphabetic cipher encryption-decryption.
CODE:
def generate_vigenere_table():
alphabet = "abcdefghijklmnopqrstuvwxyz"
table = []
for i in range(26):
table.append(alphabet[i:] + alphabet[:i])
return table

def preprocess_key(text, key):


key = key.lower().replace(" ", "")
text = text.lower().replace(" ", "")
return (key * (len(text) // len(key)) + key[:len(text) %
len(key)]).lower()

def vigenere_encrypt(plaintext, key):


plaintext = plaintext.lower().replace(" ", "")
key = preprocess_key(plaintext, key)
table = generate_vigenere_table()
ciphertext = ""

12
INFORMATION SECURITY (3170720) 191390107018

for p, k in zip(plaintext, key):


if p.isalpha():
row = ord(k) - ord('a')
col = ord(p) - ord('a')
ciphertext += table[row][col]
else:
ciphertext += p

return ciphertext

def vigenere_decrypt(ciphertext, key):


ciphertext = ciphertext.lower().replace(" ", "")
key = preprocess_key(ciphertext, key)
table = generate_vigenere_table()
plaintext = ""

for c, k in zip(ciphertext, key):


if c.isalpha():
row = ord(k) - ord('a')
col = table[row].index(c)
plaintext += chr(col + ord('a'))
else:

13
INFORMATION SECURITY (3170720) 191390107018

plaintext += c

return plaintext

if __name__ == "__main__":
choice = input("Choose mode (encrypt/decrypt): ").strip().lower()
text = input("Enter the text: ")
key = input("Enter the key: ")

if choice == "encrypt":
result = vigenere_encrypt(text, key)
print("Encrypted Text:", result)
elif choice == "decrypt":
result = vigenere_decrypt(text, key)
print("Decrypted Text:", result)
else:
print("Invalid choice. Please choose either 'encrypt' or 'decrypt'.")

14
INFORMATION SECURITY (3170720) 191390107018

OUTPUT:

15
INFORMATION SECURITY (3170720) 191390107018

PRACTICAL 6
AIM: Implement Hill cipher encryption-decryption.
CODE:
import numpy as np
from sympy import Matrix

def preprocess_text(text, block_size):


text = text.lower().replace(" ", "")
padding = (block_size - len(text) % block_size) % block_size
text += "x" * padding
return text

def text_to_matrix(text, block_size):


numbers = [ord(char) - ord('a') for char in text]
return np.array(numbers).reshape(-1, block_size)

def matrix_to_text(matrix):
flat_matrix = matrix.flatten()
return "".join(chr(num + ord('a')) for num in flat_matrix)

def encrypt_hill(plaintext, key_matrix):


block_size = key_matrix.shape[0]

16
INFORMATION SECURITY (3170720) 191390107018

plaintext = preprocess_text(plaintext, block_size)


plaintext_matrix = text_to_matrix(plaintext, block_size)

ciphertext_matrix = np.dot(plaintext_matrix, key_matrix) % 26


return matrix_to_text(ciphertext_matrix)

def decrypt_hill(ciphertext, key_matrix):


block_size = key_matrix.shape[0]
ciphertext_matrix = text_to_matrix(ciphertext, block_size)
key_matrix_mod_inverse = Matrix(key_matrix).inv_mod(26)
key_matrix_mod_inverse =
np.array(key_matrix_mod_inverse).astype(int)

plaintext_matrix = np.dot(ciphertext_matrix,
key_matrix_mod_inverse) % 26
return matrix_to_text(plaintext_matrix)

if __name__ == "__main__":
choice = input("Choose mode (encrypt/decrypt): ").strip().lower()
text = input("Enter the text: ")

n = int(input("Enter the block size (matrix size): "))


print("Enter the key matrix row by row (space-separated integers):")
17
INFORMATION SECURITY (3170720) 191390107018

key_matrix = []
for _ in range(n):
row = list(map(int, input().split()))
key_matrix.append(row)
key_matrix = np.array(key_matrix)

if choice == "encrypt":
result = encrypt_hill(text, key_matrix)
print("Encrypted Text:", result)
elif choice == "decrypt":
result = decrypt_hill(text, key_matrix)
print("Decrypted Text:", result)
else:
print("Invalid choice. Please choose either 'encrypt' or 'decrypt'.")

OUTPUT:

18
INFORMATION SECURITY (3170720) 191390107018

PRACTICAL 7
AIM: Implement Diffie-Hellman Key Exchange Method.
CODE:
import random

def diffie_hellman_key_exchange():
prime = 23
base = 5
print(f"Public Prime (p): {prime}")
print(f"Public Base (g): {base}")
private_a = random.randint(1, prime - 1)
print(f"User A's private key: {private_a}")
private_b = random.randint(1, prime - 1)
print(f"User B's private key: {private_b}")
public_a = (base ** private_a) % prime
public_b = (base ** private_b) % prime
print(f"User A's public value: {public_a}")
print(f"User B's public value: {public_b}")
shared_secret_a = (public_b ** private_a) % prime
shared_secret_b = (public_a ** private_b) % prime
assert shared_secret_a == shared_secret_b, "Shared secrets do not
match!"

19
INFORMATION SECURITY (3170720) 191390107018

print(f"Shared Secret (computed by A): {shared_secret_a}")


print(f"Shared Secret (computed by B): {shared_secret_b}")

return shared_secret_a

if __name__ == "__main__":
shared_secret = diffie_hellman_key_exchange()
print(f"\nThe shared secret key is: {shared_secret}")

OUTPUT:

20
INFORMATION SECURITY (3170720) 191390107018

PRACTICAL 8
AIM: Implement Extended Euclidean algorithm for finding the
multiplicative inverse in GF(2^n).
CODE:
def poly_add(p, q, n):
return [(p[i] + q[i]) % 2 if i < len(p) else q[i] for i in range(n)]

def poly_multiply(p, q, n):


result = [0] * (2 * n - 1) # Original size

# Calculate the maximum possible index to avoid out-of-range errors


max_index = len(p) + len(q) - 2

for i in range(len(p)):
for j in range(len(q)):
if p[i] == 1 and q[j] == 1:
# Ensure index is within bounds
if i + j < len(result):
result[i + j] ^= 1

return result[:n]

21
INFORMATION SECURITY (3170720) 191390107018

def poly_mod(p, modulus, n):


while len(p) >= len(modulus):
if p[0] == 1:
for i in range(len(modulus)):
p[i] ^= modulus[i]
p.pop(0)
return p

def extended_euclidean_algorithm(a, b, n, modulus):


r0, r1 = a, b
s0, s1 = [1] + [0] * (n - 1), [0] * n
t0, t1 = [0] * n, [1] + [0] * (n - 1)

while any(r1):
q = r0[0]
r0, r1 = r1, poly_mod(poly_add(r0, poly_multiply([q] * len(r1), r1,
n), n), modulus, n)
s0, s1 = s1, poly_add(s0, poly_multiply([q] * len(s1), s1, n), n)
t0, t1 = t1, poly_add(t0, poly_multiply([q] * len(t0), t0, n), n)

return t0

22
INFORMATION SECURITY (3170720) 191390107018

if __name__ == "__main__":
a = [1, 0, 1]
modulus = [1, 0, 1, 1]
inverse = extended_euclidean_algorithm(a, [1] * len(modulus), 3,
modulus)
print(f"The multiplicative inverse of the polynomial a(x) in GF(2^3) is:
{inverse}")

OUTPUT:

23
INFORMATION SECURITY (3170720) 191390107018

PRACTICAL 9
AIM: Implement RSA encryption-decryption algorithm.
CODE:
import random
from math import gcd

def extended_gcd(a, b):


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

def mod_inverse(a, m):


g, x, y = extended_gcd(a, m)
if g != 1:
raise ValueError("Modular inverse does not exist")
return x % m

def generate_rsa_keys(bits=8):

24
INFORMATION SECURITY (3170720) 191390107018

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

p=q=0
while not is_prime(p):
p = random.randint(2**(bits-1), 2**bits)
while not is_prime(q) or p == q:
q = random.randint(2**(bits-1), 2**bits)

n=p*q
phi_n = (p - 1) * (q - 1)
e = random.randint(2, phi_n)
while gcd(e, phi_n) != 1:
e = random.randint(2, phi_n)

d = mod_inverse(e, phi_n)

25
INFORMATION SECURITY (3170720) 191390107018

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

def rsa_encrypt(public_key, plaintext):


e, n = public_key
ciphertext = [pow(ord(char), e, n) for char in plaintext]
return ciphertext

def rsa_decrypt(private_key, ciphertext):


d, n = private_key
decrypted = ''.join([chr(pow(char, d, n)) for char in ciphertext])
return decrypted

if __name__ == "__main__":
public_key, private_key = generate_rsa_keys(bits=8)

print(f"Public Key: {public_key}")


print(f"Private Key: {private_key}")

message = "Hello"
print(f"Original Message: {message}")
ciphertext = rsa_encrypt(public_key, message)
print(f"Ciphertext: {ciphertext}")

26
INFORMATION SECURITY (3170720) 191390107018

decrypted_message = rsa_decrypt(private_key, ciphertext)


print(f"Decrypted Message: {decrypted_message}")

OUTPUT:

27
INFORMATION SECURITY (3170720) 191390107018

PRACTICAL 10

Title: Implementation of DES or AES Encryption-Decryption Techniques


Using Cryptool

Objective: To demonstrate the process of encryption and decryption


using DES (Data Encryption Standard) or AES (Advanced Encryption
Standard) algorithms using Cryptool software.

Theory:
• DES (Data Encryption Standard) is a symmetric-key block cipher
that encrypts data in 64-bit blocks using a 56-bit key.
• AES (Advanced Encryption Standard) is a symmetric-key block
cipher that encrypts data in 128-bit blocks using key sizes of 128,
192, or 256 bits.
Both encryption methods follow the principles of symmetric key
encryption, where the same key is used for both encryption and
decryption.

Materials Required:
• Cryptool software
• Computer with Windows or Linux OS

28
INFORMATION SECURITY (3170720) 191390107018

Procedure:
1. Install Cryptool:
Download and install Cryptool from the official website
(https://www.cryptool.org/en/ctool).
2. Open Cryptool:
Launch the Cryptool application.
3. Select the Algorithm:
o For DES:
▪ Navigate to "Cryptographic Algorithms" and select
"DES" from the list.
o For AES:
▪ Similarly, select "AES" from the available algorithms.
4. Input Plaintext:
o Type or paste the message (plaintext) to be encrypted in the
plaintext section of the Cryptool interface.
5. Set the Key:
o Choose or generate a key. For DES, the key size is 56 bits,
while for AES, you can choose between 128, 192, or 256 bits.
o Make sure to remember the key used for decryption.
6. Encryption:
o Click on the "Encrypt" button to perform the encryption
operation. The ciphertext will be generated and displayed in
the corresponding section.
7. Decryption:

29
INFORMATION SECURITY (3170720) 191390107018

o To decrypt the ciphertext, input the same key used for


encryption.
o Click on the "Decrypt" button, and the original plaintext
should be displayed.
8. Verification:
o Verify that the decrypted text matches the original plaintext
to ensure the encryption and decryption process was
successful.
Observations:
• Note the differences between DES and AES in terms of key size,
encryption speed, and security.
• Observe how the ciphertext changes when different keys are
used.
Results:
• The original plaintext was successfully encrypted and decrypted
using DES or AES with the provided key.
Conclusion:
• DES and AES are widely used symmetric encryption algorithms.
• Cryptool provides an intuitive interface for demonstrating and
understanding the workings of these algorithms.

30
INFORMATION SECURITY (3170720) 191390107018

31
INFORMATION SECURITY (3170720) 191390107018

32

You might also like