
Aim: To implement and demonstrate the Caesar cipher encryption and decryption technique using Python.
Aim: To implement and demonstrate the Caesar cipher encryption and decryption technique using Python.
Tools/Software Used: Python 3.x, any text editor or IDE like IDLE.
Algorithm/Procedure:
Program Code:
def caesar_encrypt(plaintext, shift):
ciphertext = ""
for char in plaintext:
if char.isalpha():
ascii_offset = 65 if char.isupper() else 97
ciphertext += chr((ord(char) - ascii_offset + shift) % 26 + ascii_offset)
else:
ciphertext += char
return ciphertext
def caesar_decrypt(ciphertext, shift):
return caesar_encrypt(ciphertext, 26 - shift)
# Input
plaintext = input("Enter plaintext: ")
shift = int(input("Enter shift value: "))
# Encryption
ciphertext = caesar_encrypt(plaintext, shift)
print("Ciphertext:", ciphertext)
# Decryption
decrypted = caesar_decrypt(ciphertext, shift)
print("Decrypted text:", decrypted)
Sample Input/Output:
Input: Plaintext = "HELLO", Shift = 3
Output: Ciphertext: KHOOR
Decrypted: HELLO
Viva Questions:
Aim: To implement Playfair cipher for encryption and decryption.
Tools/Software Used: Python 3.x.
Algorithm/Procedure:
Program Code:
def generate_matrix(key):
key = key.upper().replace("J", "I")
matrix = []
used = set()
for char in key + "ABCDEFGHIKLMNOPQRSTUVWXYZ":
if char not in used:
used.add(char)
if len(matrix) % 5 == 0:
matrix.append("")
matrix[-1] += char
return [list(row) for row in matrix]
def find_pos(matrix, char):
char = char.upper().replace("J", "I")
for i in range(5):
for j in range(5):
if matrix[i][j] == char:
return i, j
def playfair_encrypt(plaintext, key):
matrix = generate_matrix(key)
plaintext = plaintext.upper().replace("J", "I")
digraphs = ""
i = 0
while i < len(plaintext):
if i == len(plaintext) - 1 or plaintext[i] == plaintext[i+1]:
digraphs += plaintext[i] + "X"
i += 1
else:
digraphs += plaintext[i:i+2]
i += 2
ciphertext = ""
for i in range(0, len(digraphs), 2):
a, b = digraphs[i], digraphs[i+1]
pos1 = find_pos(matrix, a)
pos2 = find_pos(matrix, b)
if pos1[0] == pos2[0]: # Same row
ciphertext += matrix[pos1[0]][(pos1[1]+1)%5] + matrix[pos2[0]][(pos2[1]+1)%5]
elif pos1[1] == pos2[1]: # Same column
ciphertext += matrix[(pos1[0]+1)%5][pos1[1]] + matrix[(pos2[0]+1)%5][pos2[1]]
else: # Rectangle
ciphertext += matrix[pos1[0]][pos2[1]] + matrix[pos2[0]][pos1[1]]
return ciphertext
# Decryption similar, reverse shifts: (pos1[1]-1)%5 for row/column
def playfair_decrypt(ciphertext, key):
matrix = generate_matrix(key)
plaintext = ""
for i in range(0, len(ciphertext), 2):
a, b = ciphertext[i], ciphertext[i+1]
pos1 = find_pos(matrix, a)
pos2 = find_pos(matrix, b)
if pos1[0] == pos2[0]:
plaintext += matrix[pos1[0]][(pos1[1]-1)%5] + matrix[pos2[0]][(pos2[1]-1)%5]
elif pos1[1] == pos2[1]:
plaintext += matrix[(pos1[0]-1)%5][pos1[1]] + matrix[(pos2[0]-1)%5][pos2[1]]
else:
plaintext += matrix[pos1[0]][pos2[1]] + matrix[pos2[0]][pos1[1]]
return plaintext.replace("X", "") # Remove fillers
# Input
plaintext = input("Enter plaintext: ")
key = input("Enter key: ")
ciphertext = playfair_encrypt(plaintext, key)
print("Ciphertext:", ciphertext)
decrypted = playfair_decrypt(ciphertext, key)
print("Decrypted:", decrypted)
Sample Input/Output:
Input: Plaintext = "HIDE THE GOLD", Key = "MONARCHY"
Output: Ciphertext: BMODZBXDNAB (after processing)
Decrypted: HIDETHEGOLD
Viva Questions:
Aim: To implement a simplified DES (S-DES) for symmetric encryption.
Tools/Software Used: Python 3.x.
Algorithm/Procedure:
Program Code: (Simplified S-DES implementation)
# P10, P8, IP, EP, P4, IP inverse constants
P10 = [3,5,2,7,4,10,1,9,8,6]
P8 = [6,3,7,4,8,5,10,9]
IP = [2,6,3,1,4,8,5,7]
EP = [4,1,2,3,2,3,4,1]
P4 = [2,4,3,1]
IP_INV = [4,1,3,5,7,2,8,6]
S0 = [[1,0,3,2],[3,2,1,0],[0,2,1,3],[3,1,3,2]] # Example S-boxes (simplified)
S1 = [[0,1,2,3],[2,0,1,3],[3,0,1,0],[2,1,0,3]]
def permute(bits, table):
return ''.join(bits[i-1] for i in table)
def left_shift(bits, n):
return bits[n:] + bits[:n]
def key_gen(key):
keyp = permute(key, P10)
left, right = keyp[:5], keyp[5:]
left = left_shift(left, 1)
right = left_shift(right, 1)
k1 = permute(left + right, P8)
left = left_shift(left, 2)
right = left_shift(right, 2)
k2 = permute(left + right, P8)
return k1, k2
def f_function(right, key):
ep = permute(right, EP)
xored = ''.join(str(int(a) ^ int(b)) for a,b in zip(ep, key))
row0 = xored[0] + xored[3]
col0 = xored[1] + xored[2]
row1 = xored[4] + xored[7]
col1 = xored[5] + xored[6]
s0out = bin(S0[int(row0,2)][int(col0,2)])[2:].zfill(2)
s1out = bin(S1[int(row1,2)][int(col1,2)])[2:].zfill(2)
return permute(s0out + s1out, P4)
def sdes_encrypt(plaintext, key):
k1, k2 = key_gen(key)
ip = permute(plaintext, IP)
left, right = ip[:4], ip[4:]
left_out = right
right_out = ''.join(str(int(a) ^ int(b)) for a,b in zip(left, f_function(right, k1)))
after_swap = left_out + right_out
left, right = after_swap[:4], after_swap[4:]
left_out = right
right_out = ''.join(str(int(a) ^ int(b)) for a,b in zip(left, f_function(right, k2)))
ciphertext = permute(left_out + right_out, IP_INV)
return ciphertext
# For decryption, swap k1 and k2 in rounds
def sdes_decrypt(ciphertext, key):
k1, k2 = key_gen(key)
ip = permute(ciphertext, IP)
left, right = ip[:4], ip[4:]
left_out = right
right_out = ''.join(str(int(a) ^ int(b)) for a,b in zip(left, f_function(right, k2))) # Swap keys
after_swap = left_out + right_out
left, right = after_swap[:4], after_swap[4:]
left_out = right
right_out = ''.join(str(int(a) ^ int(b)) for a,b in zip(left, f_function(right, k1)))
plaintext = permute(left_out + right_out, IP_INV)
return plaintext
# Input (binary strings)
plaintext = input("Enter 8-bit plaintext: ")
key = input("Enter 10-bit key: ")
ciphertext = sdes_encrypt(plaintext, key)
print("Ciphertext:", ciphertext)
decrypted = sdes_decrypt(ciphertext, key)
print("Decrypted:", decrypted)
Sample Input/Output:
Input: Plaintext = "10100001", Key = "1010000010"
Output: Ciphertext: "00100111" (example, depends on S-box)
Decrypted: 10100001
Viva Questions:
Aim: To implement RSA for asymmetric encryption and decryption.
Tools/Software Used: Python 3.x.
Algorithm/Procedure:
Program Code:
import math
def gcd(a, b):
while b:
a, b = b, a % b
return a
def mod_inverse(e, phi):
for d in range(1, phi):
if (e * d) % phi == 1:
return d
return None
def generate_keys(p, q):
n = p * q
phi = (p-1) * (q-1)
e = 3
while gcd(e, phi) != 1:
e += 2
d = mod_inverse(e, phi)
return (e, n), (d, n)
def rsa_encrypt(plaintext, public_key):
e, n = public_key
return pow(plaintext, e, n)
def rsa_decrypt(ciphertext, private_key):
d, n = private_key
return pow(ciphertext, d, n)
# Input
p = int(input("Enter prime p: "))
q = int(input("Enter prime q: "))
public, private = generate_keys(p, q)
print("Public key:", public)
print("Private key:", private)
m = int(input("Enter message m (0 < m < n): "))
c = rsa_encrypt(m, public)
print("Ciphertext:", c)
decrypted = rsa_decrypt(c, private)
print("Decrypted:", decrypted)
Sample Input/Output:
Input: p=61, q=53, m=65
n=3233, e=17, d=2753
Output: Ciphertext: 2790
Decrypted: 65
Viva Questions:
Aim: To implement a basic hash function to demonstrate integrity check.
Tools/Software Used: Python 3.x.
Algorithm/Procedure:
Program Code: (Using hashlib for practical demo)
import hashlib
def sha1_hash(message):
return hashlib.sha1(message.encode()).hexdigest()
# Input
message = input("Enter message: ")
hash_value = sha1_hash(message)
print("SHA-1 Hash:", hash_value)
# Verify integrity
message2 = input("Enter message to verify: ")
if sha1_hash(message2) == hash_value:
print("Match: Integrity verified.")
else:
print("Mismatch: Tampered.")
Sample Input/Output:
Input: Message = "Hello World"
Output: SHA-1 Hash: 0a0a9f2a6772942557ab5355d76af442f8f65e01
Verification match: Yes.
Viva Questions:
Aim: To generate and verify digital signature.
Tools/Software Used: Python 3.x.
Algorithm/Procedure:
Program Code:
import hashlib
# Reuse RSA code from Practical 4
def sign_message(message, private_key):
h = int(hashlib.sha1(message.encode()).hexdigest(), 16)
d, n = private_key
signature = pow(h, d, n)
return signature
def verify_signature(message, signature, public_key):
h = int(hashlib.sha1(message.encode()).hexdigest(), 16)
e, n = public_key
decrypted_h = pow(signature, e, n)
return decrypted_h == h
# Assume keys from Practical 4
p, q = 61, 53
public, private = generate_keys(p, q)
message = input("Enter message to sign: ")
signature = sign_message(message, private)
print("Signature:", signature)
verified = verify_signature(message, signature, public)
print("Verified:", "Yes" if verified else "No")
Sample Input/Output:
Input: Message = "Secret"
Signature: (example number)
Verified: Yes
Viva Questions:
Aim: To simulate Diffie-Hellman key exchange.
Tools/Software Used: Python 3.x.
Algorithm/Procedure:
Program Code:
def mod_pow(base, exp, mod):
return pow(base, exp, mod)
p = 23 # Prime
g = 5 # Generator
# Alice
a = int(input("Alice private key a: "))
A = mod_pow(g, a, p)
print("Alice public A:", A)
# Bob
b = int(input("Bob private key b: "))
B = mod_pow(g, b, p)
print("Bob public B:", B)
# Shared
shared_alice = mod_pow(B, a, p)
shared_bob = mod_pow(A, b, p)
print("Shared key Alice:", shared_alice)
print("Shared key Bob:", shared_bob)
Sample Input/Output:
Input: a=6, b=15, p=23, g=5
A=8, B=19
Shared: 2 (matches)
Viva Questions:
Aim: To implement user authentication with hashed passwords.
Tools/Software Used: Python 3.x.
Algorithm/Procedure:
Program Code:
import hashlib
import secrets
def hash_password(password):
salt = secrets.token_hex(8)
salted = salt + password
return hashlib.sha256(salted.encode()).hexdigest() + ":" + salt
def verify_password(stored, input_pass):
hash_val, salt = stored.split(":")
salted = salt + input_pass
return hashlib.sha256(salted.encode()).hexdigest() == hash_val
# Register
passw = input("Enter password: ")
stored = hash_password(passw)
print("Stored hash:", stored)
# Login
inputp = input("Enter password to verify: ")
print("Valid:", verify_password(stored, inputp))
Sample Input/Output:
Input: Password = "pass123"
Stored: (hash:salt)
Verify "pass123": Valid True
Viva Questions:
Aim: To simulate Role-Based Access Control.
Tools/Software Used: Python 3.x.
Algorithm/Procedure:
Program Code:
# Dictionary for RBAC
roles = {
"admin": ["read", "write", "delete"],
"user": ["read"],
"guest": []
}
def check_access(user, role, action):
if action in roles.get(role, []):
return f"{user} ({role}): Access granted for {action}"
else:
return f"{user} ({role}): Access denied for {action}"
# Input
user = input("Enter user: ")
role = input("Enter role: ")
action = input("Enter action: ")
print(check_access(user, role, action))
Sample Input/Output:
Input: user=alice, role=admin, action=delete
Output: alice (admin): Access granted for delete
Viva Questions:
Aim: To perform port scanning on a local host using Nmap.
Tools/Software Used: Nmap (install on Linux/Windows), Command line.
Procedure:
Commands Executed:
$ nmap -sS 127.0.0.1
Output example:
Nmap scan report for localhost (127.0.0.1)
PORT STATE SERVICE
22/tcp open ssh
80/tcp open http
$ nmap -sV 127.0.0.1
Output: Adds version info like Apache 2.4.
Screenshot/Observation: (Describe or paste output) Open ports indicate potential vulnerabilities if not secured.
Viva Questions:
Aim: To capture and analyze network packets.
Tools/Software Used: Wireshark.
Procedure:
Observation: HTTP packets show plaintext data (e.g., user-agent). HTTPS shows encrypted.
Screenshot/Observation: Packet list shows source/dest IP, protocol HTTP, payload visible.
Viva Questions:
Aim: To set up a simple firewall rule to block a port.
Tools/Software Used: Linux terminal, iptables.
Procedure:
Commands Executed:
sudo iptables -L
Output: Chain INPUT (policy ACCEPT) target prot opt source destination DROP tcp -- anywhere anywhere tcp dpt:http
Observation: Access to port 80 blocked.
Viva Questions:
Aim: To detect ICMP ping using Snort.
Tools/Software Used: Snort (install on Linux).
Procedure:
Rule File Content:
alert icmp any any -> any any (msg:"Ping detected"; sid:1; rev:1;)
Output:
10/09-12:00:00.123456 [] [1:1:0] Ping detected [] [Priority: 0] {ICMP} 192.168.1.100 -> 192.168.1.1
Viva Questions:
Aim: To demonstrate SQL injection vulnerability and fix with prepared statements.
Tools/Software Used: Python 3.x, sqlite3.
Algorithm/Procedure:
Program Code (Vulnerable):
import sqlite3
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute('''CREATE TABLE users (user text, pass text)''')
c.execute("INSERT INTO users VALUES ('admin', 'secret')")
conn.commit()
def vulnerable_login(user, passw):
query = f"SELECT * FROM users WHERE user='{user}' AND pass='{passw}'"
print("Query:", query)
c.execute(query)
return c.fetchall()
# Demo injection
print(vulnerable_login("admin' --", "anything"))
# Output: [('admin', 'secret')] - Bypassed
Fixed Version:
def secure_login(user, passw):
query = "SELECT * FROM users WHERE user=? AND pass=?"
c.execute(query, (user, passw))
return c.fetchall()
print(secure_login("admin' --", "anything")) # []
Observation: Vulnerable allows bypass; secure prevents.
Viva Questions:
Aim: To understand simple malware behavior (do not run on real system).
Tools/Software Used: Python 3.x (simulate file replication).
Procedure:
Program Code: (Simulation)
import os
import shutil
def simulate_replicate():
current_file = __file__
for file in os.listdir("."):
if file.endswith(".py") and file != os.path.basename(current_file):
shutil.copy(current_file, file + "_infected")
print(f"Infected: {file}")
# Do not run; simulate output
print("Simulated: Would replicate to other .py files.")
Observation: Shows self-replication concept.
Viva Questions:
Aim: To perform qualitative risk assessment for a scenario.
Procedure:
Table:
| Asset | Threat | Vulnerability | Likelihood | Impact | Risk Level | Mitigation |
|---|---|---|---|---|---|---|
| Database | SQL Inj | No params | Medium | High | High | Prepared stmts |
| Web Server | DDoS | No firewall | High | Med | High | Rate limiting |
Observation: High risks need immediate action.
Viva Questions:
Aim: To simulate IP masking for anonymity.
Tools/Software Used: Python 3.x.
Procedure:
Program Code:
def simulate_vpn(original_ip, vpn_ip, destination):
print(f"Original: {original_ip} -> {destination}")
print(f"With VPN: {vpn_ip} -> {destination}")
print("Real IP hidden.")
original = "192.168.1.100"
vpn = "10.0.0.1"
dest = "8.8.8.8"
simulate_vpn(original, vpn, dest)
Output:
Original: 192.168.1.100 -> 8.8.8.8
With VPN: 10.0.0.1 -> 8.8.8.8
Real IP hidden.
Viva Questions:
This covers 17 practicals aligned to your outline. Write one per page or as per your notebook format, including code/outputs. Add diagrams if space (e.g., flowcharts for ciphers). For more, extend with tools like Metasploit demo (ethical only).
Open this section to view and download past papers
Click on Show Past Papers to load available exam papers.