CNS Lab Exam
CNS Lab Exam
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
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
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
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)
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
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
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)
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)
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!")