M.Tech - CNS LAB - AR22-2
M.Tech - CNS LAB - AR22-2
a) Ceaser Cipher
def caesar_cipher(text, shift, mode='encrypt'):
"""
Perform Caesar Cipher encryption or decryption.
Parameters:
text (str): The input text to encrypt or decrypt.
shift (int): The number of positions to shift the alphabet.
mode (str): 'encrypt' to encrypt, 'decrypt' to decrypt.
Returns:
str: The encrypted or decrypted text.
"""
if mode == 'decrypt':
shift = -shift
result = []
for char in text:
if char.isalpha():
base = ord('A') if char.isupper() else ord('a')
shifted_char = chr((ord(char) - base + shift) % 26 + base)
result.append(shifted_char)
else:
result.append(char)
return ''.join(result)
# Example usage
if __name__ == "__main__":
print("Caesar Cipher Program")
mode = input("Choose mode (encrypt/decrypt): ").strip().lower()
text = input("Enter the text: ")
shift = int(input("Enter the shift value: "))
Output:
Mode: encrypt
Input Text: Hello World
Shift: 3
Result: Khoor Zruog
b) Substitution Cipher
import string
import random
def generate_key():
"""
Generates a random substitution cipher key.
Returns:
dict: A dictionary mapping each letter to its substitution.
"""
alphabet = string.ascii_lowercase
shuffled = list(alphabet)
random.shuffle(shuffled)
return dict(zip(alphabet, shuffled))
Parameters:
text (str): The input text to encrypt or decrypt.
key (dict): The substitution cipher key.
mode (str): 'encrypt' to encrypt, 'decrypt' to decrypt.
Returns:
str: The encrypted or decrypted text.
"""
if mode == 'decrypt':
key = {v: k for k, v in key.items()} # Reverse the key for decryption
result = []
for char in text:
if char.isalpha():
is_upper = char.isupper()
substituted_char = key[char.lower()]
result.append(substituted_char.upper() if is_upper else
substituted_char)
else:
result.append(char)
return ''.join(result)
# Example usage
if __name__ == "__main__":
print("Substitution Cipher Program")
# Replace interactive inputs with predefined values for testing and non-
interactive environments
predefined_mode = 'encrypt' # Change to 'decrypt' as needed
predefined_text = "Hello World" # Replace with the text to encrypt or decrypt
if predefined_mode == 'encrypt':
key = generate_key()
print("Generated Key:", key)
else:
# Provide a predefined key for decryption
key = {
'a': 'z', 'b': 'y', 'c': 'x', 'd': 'w', 'e': 'v', 'f': 'u', 'g': 't', 'h': 's',
'i': 'r', 'j': 'q', 'k': 'p', 'l': 'o', 'm': 'n', 'n': 'm', 'o': 'l', 'p': 'k',
'q': 'j', 'r': 'i', 's': 'h', 't': 'g', 'u': 'f', 'v': 'e', 'w': 'd', 'x': 'c',
'y': 'b', 'z': 'a'
}
Output:
Mode: encrypt
Input Text: Hello World
Result: Duyyi Jihym
c) Hill Cipher
import numpy as np
# Pad plaintext if necessary to make its length a multiple of the key matrix size
n = key_matrix.shape[0]
while len(plaintext) % n != 0:
plaintext += "X" # Padding with 'X'
def main():
# Key matrix for the Hill cipher (2x2 matrix example)
key_matrix = np.array([[6, 24],
[1, 13]])
# Ensure the determinant of the key matrix is non-zero modulo 26 and invertible
determinant = int(round(np.linalg.det(key_matrix))) % 26
if determinant == 0 or np.gcd(determinant, 26) != 1:
print("The key matrix is not valid for the Hill Cipher.")
return
# Encrypt the plaintext
ciphertext = encrypt_hill_cipher(plaintext, key_matrix)
print(f"Ciphertext: {ciphertext}")
if __name__ == "__main__":
main()
Output:
Plaintext: HELLO
Encrypted: CDEGVC
Decrypted: HELLO
2. Write a python program to implement the DES algorithm.
(!pip install pycryptodome) install this package
class DESAlgorithm:
def __init__(self, key):
if len(key) != 8:
raise ValueError("Key must be 64 bits (8 bytes) long.")
self.key = key # Properly indent this line
if __name__ == "__main__":
key = b'abcdefgh' # 64-bit key (8 bytes)
plaintext = b'plaintext' # Original plaintext
des = DESAlgorithm(key)
Encrypted: 3b03c026688e671ef5eb2c5bd8b4722d
Decrypted: plaintext
3. Write a python program to implement the Blow-Fish algorithm.
class BlowfishAlgorithm:
def __init__(self, key):
# Validate key length (between 4 and 56 bytes)
if not (4 <= len(key) <= 56):
raise ValueError("Key must be between 32 bits (4 bytes) and 448 bits (56 bytes)
long.")
self.key = key # Proper indentation here
if __name__ == "__main__":
key = b'secret_k' # Key (between 4 and 56 bytes)
plaintext = b'plaintext' # Original plaintext
blowfish = BlowfishAlgorithm(key)
Output:
Encrypted: bbbef13a1625130ad75d01f360afc9b1
Decrypted: plaintext
4. Write a python program to implement the IDEA algorithm.
class IDEA:
def __init__(self, key):
if len(key) != 16:
raise ValueError("Key must be 128 bits (16 bytes) long.")
self.key = self.generate_subkeys(key)
return subkeys
t1 = x1 ^ x3
t2 = self.multiply(t1, self.key[i + 4])
t3 = (t2 + (x2 ^ x4)) & 0xFFFF
t4 = self.multiply(t3, self.key[i + 5])
t5 = (t2 + t4) & 0xFFFF
x1 ^= t4
x4 ^= t4
x2 ^= t5
x3 ^= t5
if i < 42:
x2, x3 = x3, x2
x1 = self.multiply(x1, self.key[48])
x2 = (x2 + self.key[49]) & 0xFFFF
x3 = (x3 + self.key[50]) & 0xFFFF
x4 = self.multiply(x4, self.key[51])
x1 ^= t4
x4 ^= t4
x2 ^= t5
x3 ^= t5
if i < 42:
x2, x3 = x3, x2
x1 = self.multiply(x1, inv_key[48])
x2 = (x2 - inv_key[49]) & 0xFFFF
x3 = (x3 - inv_key[50]) & 0xFFFF
x4 = self.multiply(x4, inv_key[51])
if __name__ == "__main__":
key = bytes(range(16)) # Example 128-bit key (16 bytes)
plaintext = bytes(range(8)) # Example 64-bit block (8 bytes)
idea = IDEA(key)
class AESAlgorithm:
def __init__(self, key):
# Validate key length (must be 16, 24, or 32 bytes for AES)
if len(key) not in {16, 24, 32}:
raise ValueError("Key must be 16, 24, or 32 bytes long.")
self.key = key # Correct indentation
# Create a new AES cipher object with the same key and IV
cipher = AES.new(self.key, AES.MODE_CBC, iv)
if __name__ == "__main__":
key = os.urandom(16) # Generate a random 128-bit key
plaintext = b'plaintext' # Original plaintext
Output:
Encrypted: 678361adbfd360be5e83946ec00593921367f0ba2360cd62813e9ec7f94eb7cf
Decrypted: plaintext
6. Write a python program to implement RSA algorithm.
class RSAAlgorithm:
def __init__(self, key_size=2048):
# Generate RSA private and public keys
self.private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=key_size,
backend=default_backend()
)
self.public_key = self.private_key.public_key()
def export_private_key(self):
# Export the private key in PEM format
return self.private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption()
)
def export_public_key(self):
# Export the public key in PEM format
return self.public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
if __name__ == "__main__":
rsa = RSAAlgorithm()
# Sample plaintext
plaintext = b'Hello, RSA!'
Encrypted:
4f63fd0a9675d8a3f4ed7f6f2c1e20ebca776f1635c67e04f2430948b3bf3ecc5bb4804780955
19d7c0e8e3563e803229ccb9e7858c2fab1edf89481288f507614f9bbf86b0d86341d7014bbd
09af187bf85ff1b7ea5b82d00175bf5b7a4bb5ec3cd9be774cb0768a5356081765ce0796e721
a1c8889bba3f012f587fc7b718ae870ceb35612df2227f1fbd918068bbc11240c274f4a5acfe8
37660a91343061bf274200279817884427ac46a076d4daf19a9151d4256a1f49410f0eeea83
c6b9d72606ae3bdb6873cea0b2d292c7a3b2cf39b51cff5e905de17e6d7995c570b70abc690
1b9194860d9116570cb9032c9a7bb594e366c952c8f07c9c702361b6
Decrypted: Hello, RSA!
7. Implement the Diffie-Hellman Key Exchange mechanism using python.
import random
from hashlib import sha256
class DiffieHellman:
def __init__(self):
# Public parameters (prime number and primitive root)
self.p = 23 # A small prime number (for demonstration)
self.g = 5 # A primitive root modulo p
def generate_private_key(self):
# Generate a private key
return random.randint(1, self.p - 1)
if __name__ == "__main__":
# Alice's side
alice = DiffieHellman()
alice_private_key = alice.generate_private_key()
alice_public_key = alice.generate_public_key(alice_private_key)
# Bob's side
bob = DiffieHellman()
bob_private_key = bob.generate_private_key()
bob_public_key = bob.generate_public_key(bob_private_key)
Output:
Alice's Private Key: 12
Alice's Public Key: 18
Bob's Private Key: 22
Bob's Public Key: 1
Alice's Shared Secret: 1
Bob's Shared Secret: 1
Shared secrets match!
8. Implement the SHA-1 algorithm using python.
import hashlib
class SHA1:
def __init__(self):
# Initialize SHA-1 hash object
self.sha1_hash = hashlib.sha1()
def digest(self):
"""Return the hexadecimal digest of the hash."""
return self.sha1_hash.hexdigest()
if __name__ == "__main__":
# Example input text
text = "Hello, SHA-1!"
Output:
import hashlib
class MD5:
def __init__(self):
# Initialize MD5 hash object
self.md5_hash = hashlib.md5()
def digest(self):
"""Return the hexadecimal digest of the hash."""
return self.md5_hash.hexdigest()
if __name__ == "__main__":
# Example input text
text = "Hello, MD5!"
Output:
Text: Hello, MD5!
MD5 Hash: 65a5056b6e8b4a877305f6f42790f7ec
class DSAAlgorithm:
def __init__(self):
# Generate a private key for use in the DSA algorithm
self.private_key = dsa.generate_private_key(key_size=2048,
backend=default_backend())
self.public_key = self.private_key.public_key()
if __name__ == "__main__":
# Create an instance of DSAAlgorithm
dsa_instance = DSAAlgorithm()
# Example message
message = "Hello, DSA!"
Output:
Signature:
30440220409b2a7bd6987f5a0a9ad8d50ce1ced16e964ed166d6b6c039904657929
f5e7a02207a5498d9609c7c8a2af5a1f2a5a15e25a1234b14231a0b5d76c1b919f85
0ef09
Verification: Successful