Task 1
def caesar_encrypt(plaintext, shift):
encrypted = ""
for char in plaintext:
if char.isalpha():
# Convert char to 0-25 range
offset = 65 if char.isupper() else 97
encrypted_char = chr((ord(char) - offset + shift) % 26 + offset)
encrypted += encrypted_char
else:
encrypted += char # Non-alphabetic characters are not changed
return encrypted
def caesar_decrypt(ciphertext, shift):
decrypted = ""
for char in ciphertext:
if char.isalpha():
offset = 65 if char.isupper() else 97
decrypted_char = chr((ord(char) - offset - shift) % 26 + offset)
decrypted += decrypted_char
else:
decrypted += char
return decrypted
# Step 1: Ask the user for plaintext and shift value
plaintext = input("Enter the plaintext: ")
shift = int(input("Enter the shift value (0-25): "))
# Step 2: Encrypt
ciphertext = caesar_encrypt(plaintext, shift)
# Step 3: Decrypt
decrypted_text = caesar_decrypt(ciphertext, shift)
# Step 4: Print the results
print("\nEncrypted text:", ciphertext)
print("Decrypted text:", decrypted_text)
Task 2:
def key_vigenere(key):
keyArray = []
for i in range(0, len(key)):
keyElement = ord(key[i].upper()) - 65
keyArray.append(keyElement)
return keyArray
secretKey = 'DECLARATION'
key = key_vigenere(secretKey)
print(key)
Task 3
def simple_encrypt(plaintext, key):
"""Encrypts using simple XOR with a single byte key."""
return bytes([b ^ key for b in plaintext.encode()])
def simple_decrypt(ciphertext, key):
"""Decrypts using simple XOR with a single byte key."""
return ''.join([chr(b ^ key) for b in ciphertext])
# Step 1: Ask the user for plaintext message
plaintext = input("Enter plaintext message: ")
print("Simulating DES using XOR and 8-bit key (0-255)...")
# Step 2: Simulate encryption using a user-chosen 8-bit key
correct_key = int(input("Enter an 8-bit key (0-255) to encrypt the
message: "))
ciphertext = simple_encrypt(plaintext, correct_key)
print("Encrypted message (in bytes):", ciphertext)
# Step 3: Brute-force attack simulation
print("\nStarting brute-force attack...")
found = False
for key_guess in range(256): # 8-bit key space = 0 to 255
decrypted = simple_decrypt(ciphertext, key_guess)
if decrypted.isprintable() and decrypted == plaintext:
print(f"\nCorrect key found: {key_guess}")
print("Decrypted message:", decrypted)
found = True
break
if not found:
print("Key not found.")
Task 4
import hashlib
import os
# Step 1: Generate a random salt
def generate_salt(length=16):
return os.urandom(length) # Generates a random byte string
# Step 2: Hash password + salt using SHA-256
def hash_password(password, salt):
# Ensure password is bytes before concatenation
return hashlib.sha256(password.encode() + salt).hexdigest()
# Step 3: Store salt and hash (simulation)
def store_password(password):
salt = generate_salt()
password_hash = hash_password(password, salt)
return salt, password_hash
# Function to verify a password using stored salt and hash
def verify_password(stored_salt, stored_hash, password_attempt):
attempt_hash = hash_password(password_attempt, stored_salt)
return attempt_hash == stored_hash
# Example usage
user_password = input("Enter a password to store: ")
salt, hashed = store_password(user_password)
print("\n[Stored]")
print("Salt (hex):", salt.hex())
print("Hashed Password:", hashed)
# Verify password
attempt = input("\nRe-enter password to verify: ")
if verify_password(salt, hashed, attempt):
print("Password verified successfully!")
else:
print("Incorrect password!")
Task 5
import hmac
import hashlib
# Step 1: Define Secret Key
secret_key = b'111' # Must be bytes
# Step 2: Initialize HMAC Object
hmac_obj = hmac.new(secret_key, digestmod=hashlib.sha256)
# Step 3: Open the Target File
file_path = 'hello.txt' # This file should contain the text "Hello"
try:
with open(file_path, 'rb') as f:
# Step 4: Read the File in Chunks
while chunk := f.read(1024): # Reads 1024-byte chunks
# Step 5: Process Each Chunk
hmac_obj.update(chunk)
# Step 6: Finalize and Retrieve Digest
digest = hmac_obj.hexdigest()
# Step 7: Output the Digest
print(f"HMAC Digest (hex): {digest}")
except FileNotFoundError:
print(f"File '{file_path}' not found. Please create it with the content:
Hello")
Task 6
import hashlib
import time
class Block:
def __init__(self, index, data, previous_hash):
self.index = index
self.timestamp = time.time()
self.data = data
self.previous_hash = previous_hash
self.hash = self.compute_hash()
def compute_hash(self):
block_content = f"{self.index}{self.timestamp}{self.data}
{self.previous_hash}"
return hashlib.sha256(block_content.encode()).hexdigest()
# Sample usage
genesis_block = Block(0, "Genesis Block", "0")
print("Block #", genesis_block.index)
print("Timestamp:", genesis_block.timestamp)
print("Data:", genesis_block.data)
print("Previous Hash:", genesis_block.previous_hash)
print("Hash:", genesis_block.hash)
Task 7:
import os
# Step 1: Generate a random key (same length as message)
def generate_key(length):
return os.urandom(length)
# Step 2: Encrypt using XOR
def encrypt(message, key):
message_bytes = message.encode()
encrypted = bytes([mb ^ kb for mb, kb in zip(message_bytes, key)])
return encrypted
# Step 3: Decrypt using XOR
def decrypt(ciphertext, key):
decrypted_bytes = bytes([cb ^ kb for cb, kb in zip(ciphertext, key)])
return decrypted_bytes.decode()
# User 1 - Send Message
message = input("User 1, enter your message: ")
key = generate_key(len(message))
ciphertext = encrypt(message, key)
print("\nEncrypted Message (in bytes):", ciphertext)
# User 2 - Receive and Decrypt
decrypted_message = decrypt(ciphertext, key)
print("\nUser 2 received and decrypted the message:",
decrypted_message)
# Step 4: Destroy the key
del key
print("\nThe key has been securely destroyed.")