0% found this document useful (0 votes)
26 views8 pages

CNS Lab Exam

The document contains multiple programs demonstrating various encryption techniques, including Caesar Cipher, Monoalphabetic Cipher, Hill Cipher, Vigenere Cipher, One Time Pad, Rail Fence, RSA, SHA, Diffie-Hellman, MD5, Brute Force Attack, and Digital Signature. Each program provides a method for either encrypting or decrypting messages using the specified algorithm. The examples illustrate how to implement these ciphers and their respective functionalities in Python.
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)
26 views8 pages

CNS Lab Exam

The document contains multiple programs demonstrating various encryption techniques, including Caesar Cipher, Monoalphabetic Cipher, Hill Cipher, Vigenere Cipher, One Time Pad, Rail Fence, RSA, SHA, Diffie-Hellman, MD5, Brute Force Attack, and Digital Signature. Each program provides a method for either encrypting or decrypting messages using the specified algorithm. The examples illustrate how to implement these ciphers and their respective functionalities in Python.
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/ 8

PROGRAM 1

CEASAR CIPHER
def caesar_cipher(text, shift, mode='encrypt'):
result = ''
for char in text:
if char.isalpha():
shift *= 1 if mode == 'encrypt' else -1
ascii_offset = ord('A') if char.isupper() else ord('a')
result += chr((ord(char) - ascii_offset + shift) % 26 + ascii_offset)
else:
result += char
return result

print(caesar_cipher("Hello, World!", 3, 'encrypt'))


print(caesar_cipher("Khoor, Zruog!", 3, 'decrypt'))

PROGRAM 2
MONOALPHABETIC
def monoalpha_cipher(txt, key, mode='e'):
a = "abcdefghijklmnopqrstuvwxyz"
m = dict(zip(a, key)) if mode == 'e' else dict(zip(key, a))
return ''.join(m.get(c, c) for c in txt.lower())

k = "phqgiumeaylnofdxjkrcvstzwb"
t = "hello world"
c = monoalpha_cipher(t, k)
print("Encrypted:", c)
print("Decrypted:", monoalpha_cipher(c, k, 'd'))
PROGRAM 3
HILL CIPHER
import numpy as np

def hill_cipher(text, key):


text = text.lower().replace(" ", "")
while len(text) % 3 != 0:
text += 'x'

key_matrix = np.array(key).reshape(3, 3)
alphabet = "abcdefghijklmnopqrstuvwxyz"
text_vector = [alphabet.index(c) for c in text]
text_matrix = np.array(text_vector).reshape(-1, 3).T

cipher_matrix = np.dot(key_matrix, text_matrix) % 26


cipher_text = ''.join(alphabet[i] for i in cipher_matrix.T.flatten())
return cipher_text

key = [6, 24, 1, 13, 16, 10, 20, 17, 15]


text = "hello"
cipher = hill_cipher(text, key)
print("Encrypted:", cipher)

PROGRAM 4
VIGNERE CIPHER
def vigenere_cipher(text, key, mode='e'):
a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
key = (key * (len(text) // len(key) + 1))[:len(text)]
shift = 1 if mode == 'e' else -1
result = []
for t, k in zip(text, key):
if t in a:
new_char = a[(a.index(t) + shift * a.index(k)) % len(a)]
result.append(new_char)
else:
result.append(t)

return ''.join(result)

text, key = "Hello123", "Key42"


cipher = vigenere_cipher(text, key)
print("Encrypted:", cipher)
print("Decrypted:", vigenere_cipher(cipher, key, 'd'))

PROGRAM 5
ONE TIME PAD
import os

def otp_encrypt(text):
key = os.urandom(len(text))
cipher = bytes([t ^ k for t, k in zip(text.encode(), key)])
return cipher, key

def otp_decrypt(cipher, key):


return bytes([c ^ k for c, k in zip(cipher, key)]).decode()

text = "HelloWorld"
cipher, key = otp_encrypt(text)
print("Cipher:", cipher)
print("Decrypted:", otp_decrypt(cipher, key))

PROGRAM 6
RAIL FENCE
def rail_fence_encrypt(text, rails):
fence = [[] for _ in range(rails)]
rail, step = 0, 1
for char in text:
fence[rail].append(char)
rail += step
if rail == 0 or rail == rails - 1:
step *= -1
return ''.join(''.join(row) for row in fence)

text = "HELLOWORLD"
cipher = rail_fence_encrypt(text, 3)
print("Encrypted:", cipher)

PROGRAM 7
RSA
p = 61
q = 53
n=p*q
phi = (p - 1) * (q - 1)
e = 17
d = pow(e, -1, phi)
def encrypt(message, e, n):
return [(ord(char) ** e) % n for char in message]
message = "HI"
ciphertext = encrypt(message, e, n)
print("Ciphertext:", ciphertext)

PROGRAM 8
SSH
import hashlib

def sha_encrypt(message):
"""Encrypts a message using SHA-256."""
message = str(message) # Ensure it's a string
sha256_hash = hashlib.sha256(message.encode()).hexdigest()
return sha256_hash

message = input("Enter a message: ")


hash_value = sha_encrypt(message)

print("SHA-256 Hash:", hash_value)

PROGRAM 9
DIFFIE HELLMAN
import random
# Step 1: Agree on public values (a prime number and a base)
prime = 23 # Small prime number (p)
base = 5 # Primitive root modulo p (g)

# Step 2: Each party selects a private key


alice_private = random.randint(1, prime - 1) # Alice's private key
bob_private = random.randint(1, prime - 1) # Bob's private key

# Step 3: Compute public keys


alice_public = (base ** alice_private) % prime # A = g^a mod p
bob_public = (base ** bob_private) % prime # B = g^b mod p

# Step 4: Exchange public keys and compute shared secret


alice_shared_secret = (bob_public ** alice_private) % prime # S = B^a mod p
bob_shared_secret = (alice_public ** bob_private) % prime # S = A^b mod p

# Step 5: Verify both computed the same shared secret


print("Alice's Shared Secret:", alice_shared_secret)
print("Bob's Shared Secret:", bob_shared_secret)

# If Diffie-Hellman worked, both values should be the same


assert alice_shared_secret == bob_shared_secret, "Key Exchange Failed!"
print("Secure Key Exchange Successful! 🔑")

PROGRAM 10
MD5
import hashlib

def md5_encrypt(message):
"""Encrypts a message using MD5."""
md5_hash = hashlib.md5(message.encode()).hexdigest()
return md5_hash

# Example usage
message = input("Enter a message: ")
hash_value = md5_encrypt(message)

print("MD5 Hash:", hash_value)


PROGRAM 11
BRUTE FORCE ATTACK
def additive_cipher_decrypt(ciphertext, shift):
"""Decrypts an additive cipher (Caesar cipher) using a given shift."""
plaintext = ""
for char in ciphertext:
if char.isalpha(): # Only decrypt alphabetic characters
shifted = chr(((ord(char.upper()) - 65 - shift) % 26) + 65)
plaintext += shifted if char.isupper() else shifted.lower()
else:
plaintext += char # Keep non-alphabetic characters unchanged
return plaintext

def brute_force_attack(ciphertext):
"""Attempts all possible shifts (0-25) to find the original plaintext."""
print("Brute Force Attack Results:")
for shift in range(26):
decrypted_text = additive_cipher_decrypt(ciphertext, shift)
print(f"Shift {shift}: {decrypted_text}")

# Example usage
ciphertext = input("Enter the ciphertext: ")
brute_force_attack(ciphertext)

PROGRAM 12
DIGITAL SIGNATURE
import hashlib

# Message to sign
message = "Hello, Digital Signature!"
# Generate a simple signature (hash of message)
signature = hashlib.sha256(message.encode()).hexdigest()

# Verify signature
new_signature = hashlib.sha256(message.encode()).hexdigest()

if signature == new_signature:
print("Signature is valid!")
else:
print("Signature is invalid!")

You might also like