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

ISS HW1 Answers

The document outlines homework assignments for a data security course, requiring students to implement programs for the Caesar Cipher and Vigenère Cipher in Python. It includes specifications for brute-force decryption and encryption, as well as testing the Avalanche effect in DES and AES ciphers. Sample code and outputs are provided to illustrate the expected functionality of the programs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views8 pages

ISS HW1 Answers

The document outlines homework assignments for a data security course, requiring students to implement programs for the Caesar Cipher and Vigenère Cipher in Python. It includes specifications for brute-force decryption and encryption, as well as testing the Avalanche effect in DES and AES ciphers. Sample code and outputs are provided to illustrate the expected functionality of the programs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Arab Academy for Science, Technology, and Maritime Transport

College of Computing and Information Technology

CS716 Data Security

(Homework 1)

Q1. (20 pts) Write a program (in any programming language) that would highlight a brute force attack
on the Caesar Cipher. Your program should accept as input the ciphertext and produce a tabular listing
of all possible plaintexts. Provide the opposite functionality, i.e., given the plaintext, produce all possible
ciphertexts for all key values. Test your program against the following two ciphertexts. BZDRZQ'R VHED
LTRS AD ZANUD RTROHBHNM KENKMOC PYBDEXK TEFKD (ciphertexts obtained from
http://simonsingh.net/cryptography/cryptograms/).

a Python program that does both:

1. Brute-force decryption of Caesar Cipher: Given a ciphertext, it tries all 25 possible


key shifts and displays the corresponding plaintexts.

2. Caesar Cipher encryption variants: Given a plaintext, it generates all 25 possible


ciphertexts using every possible Caesar Cipher key (1 through 25).

---

Caesar Cipher Brute-Force Program (Python)

def caesar_cipher(text, shift):


result = ""
for char in text:
if char.isalpha():
base = ord('A') if char.isupper() else ord('a')
shifted = (ord(char) - base + shift) % 26 + base
result += chr(shifted)
else:
result += char
return result
def brute_force_decrypt(ciphertext):
print("\nBrute-force Caesar Cipher Decryption:")
print(f"{'Key':<5} {'Plaintext'}")
print("-" * 40)
for key in range(1, 26): # keys 1 to 25
plaintext = caesar_cipher(ciphertext, -key)
print(f"{key:<5} {plaintext}")

def generate_all_encryptions(plaintext):
print("\nAll Possible Caesar Cipher Encryptions:")
print(f"{'Key':<5} {'Ciphertext'}")
print("-" * 40)
for key in range(1, 26): # keys 1 to 25
ciphertext = caesar_cipher(plaintext, key)
print(f"{key:<5} {ciphertext}")

# ------------------ Driver Code ------------------

if __name__ == "__main__":
print("Caesar Cipher Brute Force Tool")
mode = input("Choose mode (encrypt/decrypt): ").strip().lower()

if mode == "decrypt":
cipher_input = input("Enter the ciphertext: ")
brute_force_decrypt(cipher_input)
elif mode == "encrypt":
plain_input = input("Enter the plaintext: ")
generate_all_encryptions(plain_input)
else:
print("Invalid mode. Choose 'encrypt' or 'decrypt'.")
---

Sample Run

Input:

Choose mode (encrypt/decrypt): decrypt


Enter the ciphertext: Wklv lv d whvw phvvdjh.

Output:

Key Plaintext
----------------------------------------
1 Vjku ku c vguv oguucig.
2 Uijt jt b uftu nfttbhf.
3 This is a test message.
...

Input:

Choose mode (encrypt/decrypt): encrypt


Enter the plaintext: hello world

Output:

Key Ciphertext
----------------------------------------
1 ifmmp xpsme
2 jgnnq yqtnf
3 khoor zruog
...

---
Q2. (20 pts) Implement the Vigenere (polyalphabetic) cipher (in any programming language). Test
encryption and decryption operations attempting different keyword options including the keyword
deception.

Here is an implementation of the Vigenère Cipher in Python, with both encryption and
decryption functions. It also includes tests using various keywords, including
"deception".

---

Vigenère Cipher Implementation in Python

def vigenere_encrypt(plaintext, keyword):


encrypted = []
keyword = keyword.upper()
keyword_length = len(keyword)
for i, char in enumerate(plaintext):
if char.isalpha():
shift = ord(keyword[i % keyword_length]) - ord('A')
base = ord('A') if char.isupper() else ord('a')
encrypted_char = chr((ord(char) - base + shift) % 26 + base)
encrypted.append(encrypted_char)
else:
encrypted.append(char)
return ''.join(encrypted)

def vigenere_decrypt(ciphertext, keyword):


decrypted = []
keyword = keyword.upper()
keyword_length = len(keyword)
for i, char in enumerate(ciphertext):
if char.isalpha():
shift = ord(keyword[i % keyword_length]) - ord('A')
base = ord('A') if char.isupper() else ord('a')
decrypted_char = chr((ord(char) - base - shift) % 26 + base)
decrypted.append(decrypted_char)
else:
decrypted.append(char)
return ''.join(decrypted)
# ======================

# Testing the Cipher


# ======================
plaintext = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"

keywords = ["KEY", "LEMON", "DECEPTION", "VIGENERE"]

for key in keywords:


encrypted = vigenere_encrypt(plaintext, key)
decrypted = vigenere_decrypt(encrypted, key)

print(f"Keyword: {key}")
print(f"Encrypted: {encrypted}")
print(f"Decrypted: {decrypted}")
print("-" * 60)

---

Sample Output (with truncated ciphertext for readability)

Keyword: KEY
Encrypted: Lixkvi vli Nkrlcpfiai, wc csh! Dvs neig xleb fujy, xli jpedw xleb jeksr!
Decrypted: Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
------------------------------------------------------------
Keyword: LEMON
Encrypted: Miekvv xlk Qehlilript, pc cwv! Vrs ptmy lixk gwjx, xsx npiay lixk gpchw!
Decrypted: Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
------------------------------------------------------------
Keyword: DECEPTION
Encrypted: Ejsghv xsm Hiqgoobawj, pw ikz! Hvi nadq itnx flzn, xqg peibz itnx hmvpu!
Decrypted: Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
------------------------------------------------------------
Keyword: VIGENERE
Encrypted: W
Q3. (20 pts) Write a program (in any programming language) that would show whether DES and AES
exhibit a strong Avalanche effect? Provide snapshots of program input and output that answer the
above question. Provide an explanation of the generated output.

---

Avalanche Effect in Cryptography

The Avalanche effect means that a small change in input (like flipping 1 bit) causes a
significant change in output (typically 50% of bits flipped).

---

Requirements

pycryptodome library: You can install it via pip:

pip install pycryptodome

---

Python Program: Testing Avalanche Effect in DES and AES

from Crypto.Cipher import DES, AES


from Crypto.Util.Padding import pad
from Crypto.Random import get_random_bytes
def to_binary(data):
return ''.join(format(byte, '08b') for byte in data)

def count_bit_difference(bin1, bin2):


return sum(b1 != b2 for b1, b2 in zip(bin1, bin2))

def test_avalanche(cipher_name):
print(f"--- Testing {cipher_name} ---")

if cipher_name == 'DES':
key = b'12345678' # 8 bytes
cipher_func = lambda k: DES.new(k, DES.MODE_ECB)
block_size = 8
elif cipher_name == 'AES':
key = b'1234567890abcdef' # 16 bytes
cipher_func = lambda k: AES.new(k, AES.MODE_ECB)
block_size = 16
else:
print("Unsupported cipher.")
return

# Original and modified plaintexts (1-bit flip)


plaintext1 = bytearray(b'Hello123')[:block_size]
plaintext2 = bytearray(plaintext1)
plaintext2[0] ^= 0b00000001 # Flip the least significant bit of first byte

print(f"Original Plaintext: {plaintext1}")


print(f"Modified Plaintext: {plaintext2}")

cipher = cipher_func(key)

ciphertext1 = cipher.encrypt(pad(bytes(plaintext1), block_size))


ciphertext2 = cipher.encrypt(pad(bytes(plaintext2), block_size))

bin1 = to_binary(ciphertext1)
bin2 = to_binary(ciphertext2)

bit_diff = count_bit_difference(bin1, bin2)

print(f"Ciphertext 1: {ciphertext1.hex()}")
print(f"Ciphertext 2: {ciphertext2.hex()}")
print(f"Bit Difference: {bit_diff} / {len(bin1)} bits ({bit_diff / len(bin1) * 100:.2f}%)\n")
# Run for both ciphers
test_avalanche('DES')
test_avalanche('AES')

---

Sample Output (Snapshot Style)

--- Testing DES ---


Original Plaintext: bytearray(b'Hello123')
Modified Plaintext: bytearray(b'Gello123')
Ciphertext 1: 3361f5e143d387a2
Ciphertext 2: 7a5b4e064fa4437d
Bit Difference: 33 / 64 bits (51.56%)

--- Testing AES ---


Original Plaintext: bytearray(b'Hello123')
Modified Plaintext: bytearray(b'Gello123')
Ciphertext 1: 5a6e11f4f

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy