0% found this document useful (0 votes)
14 views12 pages

Information Security Lab Work

It's about information security practical work which is about cipher

Uploaded by

ghorif227
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)
14 views12 pages

Information Security Lab Work

It's about information security practical work which is about cipher

Uploaded by

ghorif227
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/ 12

An Expert's Guide to Classical Encryption:

Theory, Cryptanalysis, and Python


Implementation
1: The Foundations of Cryptography
1.1 The Discipline of Cryptography

Cryptography is the scientific discipline dedicated to the secure and secret communication of
information. At its core, it is the art of obfuscating messages to render them unintelligible to anyone
other than the intended recipient. This process, known as encryption, converts an original, human
readable message, or plaintext, into an encoded, incomprehensible format called ciphertext. The
reverse process, which restores the ciphertext to its original plaintext form, is called decryption.
The fundamental element that governs both of these transformations is the key, a secret value,
string, or file that orchestrates all the substitutions and transformations performed by the
encryption algorithm.

The field of cryptography stands in a unique, co-dependent relationship with its adversarial
counterpart, cryptanalysis. While cryptography focuses on designing robust systems to protect
data, cryptanalysis is the practice of analyzing and breaking those very systems to uncover hidden
weaknesses and decipher encrypted data without access to the secret key. This is not merely a
malicious pursuit; cryptanalysis plays a critical and constructive role in the ongoing evolution of
secure communication. As weaknesses are discovered by cryptanalysts, cryptographers are
compelled to innovate and create stronger, more resilient encryption methods, thereby
continuously raising the bar for digital security. This perpetual cycle of challenge and innovation
forms the bedrock of modern cybersecurity.

1.2 The Symmetric Cipher Model: An Architectural Blueprint

The symmetric cipher model represents the oldest and most foundational approach to encryption,
utilizing a single, shared secret key for both encryption and decryption. This is often referred to as
single-key encryption. The model provides a blueprint for secure communication between a sender
and a receiver, built upon five essential components:

1. Plain Text (x): This is the original, unencrypted message that the sender wishes to
communicate securely.
2. Secret Key (k): A value that is shared between the sender and receiver and is known
only to them. It is independent of the encryption algorithm itself but governs every
substitution and transformation that occurs.
3. Encryption Algorithm (E): A mathematical or procedural function that takes the
plaintext and the secret key as inputs and produces the ciphertext as output. It is
expressed mathematically as E(x,k)=y.
4. Cipher Text (y): The output of the encryption process. It is a scrambled, unreadable
version of the plaintext that is transmitted through a communication channel.
5. Decryption Algorithm (D): The inverse function of the encryption algorithm. It takes
the ciphertext and the same secret key as inputs to produce the original plaintext,
expressed as D(y,k)=x.

The simplicity and speed of symmetric ciphers make them highly beneficial for bulk data
encryption. However, the model's most significant challenge lies in the secure distribution and
management of the secret key. The entire security of the system hinges on the secrecy of this
single key. If a malicious actor intercepts the key during its exchange between the sender and
receiver, the entire communication system is compromised. This key management vulnerability
is a primary motivation for the development of alternative cryptographic models, such as
asymmetric or public-key cryptography, where the need for a shared secret is eliminated.

Table A.1: The Symmetric Cipher Model Components

Component Description Example


Plain Text (x) The original, readable message. hello
The secret value used for encryption and
Secret Key (k) 5
decryption.
Encryption Algorithm The function that encrypts the plaintext using encrypt(hello,
(E) the key. 5)
The unreadable output of the encryption
Cipher Text (y) mjqqt
process.
Decryption Algorithm The function that decrypts the ciphertext using decrypt(mjqqt,
(D) the key. 5)

2: The Symmetric Cipher Model: A Basic Python Example


2.1 Implementing the Symmetric Cipher Model

In a classroom setting, the Caesar Cipher is often used to illustrate the symmetric cipher model.
The following Python code demonstrates a simplified symmetric cipher model using a basic
Caesar cipher for illustration. This model includes functions for encryption and decryption using
the same shift value (key). The code uses basic arithmetic and loops, which are fundamental
concepts in Python.

Example 2.1.1: Basic Encryption and Decryption

This example demonstrates the core symmetric encryption and decryption process on a simple
string of data. The same key is used for both operations, reflecting the single-key principle of the
model.

Python
def symmetric_cipher(text, shift, mode='encrypt'):
"""
A basic symmetric cipher function using a Caesar cipher.
The key is the shift value.
"""
if mode == 'decrypt':
shift = -shift

result = ""
for char in text:
if 'a' <= char <= 'z':
start = ord('a')
shifted = (ord(char) - start + shift) % 26
result += chr(start + shifted)
elif 'A' <= char <= 'Z':
start = ord('A')
shifted = (ord(char) - start + shift) % 26
result += chr(start + shifted)
else:
result += char # Non-alphabetic characters remain unchanged
return result

# Example 1: Encrypting a message


message = "hello world"
key = 3
encrypted_message = symmetric_cipher(message, key, mode='encrypt')
print(f"Original: {message}")
print(f"Encrypted: {encrypted_message}")

Atbash Cipher
Objective:
Implement the Atbash Cipher, a simple substitution cipher that reverses the
alphabet Tools: Python Tasks:

Create a mapping where A maps to Z, B to Y, etc.


Implement encryption and decryption (same function due to symmetry).
Test with sample plaintext.
Sample Code:
def atbash_cipher(text):
result = ""
for char in text.upper():
if char.isalpha():
result += chr(90 - (ord(char) - 65)) # Z is 90, A is 65
else:
result += char
return result

# Example usage
plaintext = "ATTACK AT DAWN"
ciphertext = atbash_cipher(plaintext)
decrypted = atbash_cipher(ciphertext) # Same function for decryption
print(f"Plaintext: {plaintext}")
print(f"Ciphertext: {ciphertext}")
print(f"Decrypted: {decrypted}")

Sample Output:
Plaintext: ATTACK AT DAWN
Ciphertext: ZGGZXP ZG WZDM
Decrypted: ATTACK AT DAWN

Explanation:
The Atbash Cipher is a monoalphabetic substitution with a fixed reverse
mapping, differing from Caesar, Vigenère, or Affine ciphers in prior examples
by its simplicity and symmetry, requiring no key.

3: Cryptanalysis: The Art of Breaking Codes


3.1 The Duality of Cryptography and Cryptanalysis

Cryptography and cryptanalysis are two sides of the same coin. Cryptography is concerned with
creating methods for secure communication, while cryptanalysis is the field dedicated to finding
weaknesses in those methods and breaking them. While seemingly an adversarial relationship,
this dynamic is, in fact, symbiotic. Cryptanalysts, often likened to ethical hackers, test the limits
of cryptographic systems to identify flaws and vulnerabilities. This constant pressure to break
ciphers compels cryptographers to build more robust and sophisticated systems, such as
increasing RSA key lengths after a vulnerability was exposed. This is an ongoing co-
evolutionary struggle, a continuous cycle where the act of breaking a cipher ultimately serves to
strengthen the field as a whole.

3.2 A Deep Dive into the Brute-Force Attack

A brute-force attack is a trial-and-error method used to crack passwords, login credentials, or


encryption keys by systematically trying every possible combination until the correct one is
found. This is one of the most fundamental and straightforward cryptanalytic techniques. The
effectiveness of a brute-force attack is directly tied to the size of the key space. A small, limited
key space makes a brute-force attack a simple and guaranteed method for decryption. For
instance, a Caesar cipher, with its mere 25 possible keys, is highly vulnerable and can be broken
in a matter of seconds by a modern computer. The core principle is that as long as the
computational resources are sufficient, the attack is guaranteed to succeed.

Modern brute-force attacks have evolved beyond simple trial-and-error, incorporating various
methods to increase efficiency and avoid detection.

• Simple Brute-Force: This involves a manual or automated guess of all possible


combinations. It is effective against short, weak passwords or PINs.
• Dictionary Attack: A more refined approach that uses a pre-compiled list of common
words, phrases, and passwords. This method is more efficient than a full brute-force as it
exploits the common human tendency to use simple, guessable passwords.
• Hybrid Attack: This method combines a dictionary attack with brute-force techniques.
An attacker will start with words from a dictionary and then systematically append or
prepend numbers, symbols, or variations to them (e.g., password123 or P@ssword!).
• Reverse Brute-Force: Instead of guessing a password for a known username, this attack
starts with a known password (often from a data breach) and attempts to find a matching
username from a large list of accounts.
• Password Spraying: This technique attempts a single, common password against a large
number of usernames to avoid triggering account lockout policies that are designed to
thwart traditional brute-force attacks.

Table A.2: Common Brute-Force Attack Types

Attack Type Description Example


Simple Brute- Systematically tries every possible key Guessing a 4-digit PIN by trying
Force or combination. 0000, 0001, 0002,...
Dictionary Tries passwords from a predefined list Attempting 123456, password, or
Attack of words and common phrases. qwerty against an account.
Combines a dictionary attack with Trying password1, password2,
Hybrid Attack
simple brute-force methods. Password123, etc.
Reverse Brute- Starts with a known password and Using Summer2023! as a password to
Force searches for a matching username. find all accounts that use it.

3.3 Other Foundational Cryptanalytic Techniques

Beyond brute-force, several other techniques have been historically significant for breaking
classical ciphers.

• Frequency Analysis: This method exploits the predictable statistical properties of


language. By analyzing the frequency of letters in the ciphertext and comparing it to the
known frequency of letters in the original language (e.g., 'E' is the most common letter in
English), a cryptanalyst can deduce the mapping and, in turn, the key. This is highly
effective against ciphers that use a fixed substitution, such as the Caesar cipher.
• Known-Plaintext Attack: This is a powerful attack model where the adversary has
access to both a section of the plaintext and its corresponding ciphertext. By comparing
the two, the attacker can quickly and easily determine the key and subsequently decrypt
the rest of the message.
• Crib Dragging: This technique is a variation of the known-plaintext attack. The
cryptanalyst uses a known or likely phrase (a "crib"), such as "the" or "E-mail," and
attempts to align it with various parts of the ciphertext. Once a match is found, the
attacker can deduce a portion of the key, which can then be used to decrypt the entire
message.

4: Cryptanalysis in Action: Python Implementations


The following Python examples provide practical demonstrations of how the cryptanalytic
techniques discussed in 3 are implemented.
4.1 Implementing a Simple Brute-Force Attack

Example 4.1.1: Brute-Forcing a 4-Digit PIN

This script provides a conceptual and simple demonstration of a brute-force attack. It iterates
through every possible 4-digit combination to find a target PIN.

Python
import time

def brute_force_pin(target_pin):
start_time = time.time()
for i in range(10000):
# Format the number as a 4-digit string
guess = f"{i:04d}"
print(f"Trying PIN: {guess}")

if guess == target_pin:
end_time = time.time()
duration = end_time - start_time
print(f"\nSuccess! Found the PIN: {guess}")
print(f"Time taken: {duration:.2f} seconds")
return True
return False

# Simulate a target PIN


target_pin = "8531"
brute_force_pin(target_pin)

Example 4.1.2: A Dictionary Attack Against a Password List

A dictionary attack is more efficient than a simple brute-force attack because it uses a targeted
list of common passwords, exploiting a common security vulnerability: human predictability.

Python
import hashlib

def dictionary_attack(target_hash, password_list_file):


with open(password_list_file, 'r') as f:
password_list = [line.strip() for line in f]

print("Beginning dictionary attack...")


for password in password_list:
hashed_guess = hashlib.sha256(password.encode()).hexdigest()
print(f"Trying password: {password}...")

if hashed_guess == target_hash:
print(f"\nSuccess! Found the password: {password}")
return True

print("\nAttack failed. Password not in dictionary.")


return False
# Simulate a password hash
target_password = "cat"
target_hash = hashlib.sha256(target_password.encode()).hexdigest()

# Create a dummy password list file for the example


with open('dictionary.txt', 'w') as f:
f.write('dog\n')
f.write('apple\n')
f.write('cat\n')
f.write('password\n')

dictionary_attack(target_hash, 'dictionary.txt')

5: Substitution Techniques
5.1 The Principles of Substitution Ciphers

Substitution ciphers represent a broad class of algorithms where each character in the plaintext is
systematically replaced, or substituted, with a different character or symbol to produce the
ciphertext. The core principle is a one-to-one character mapping, where a character in the
original message always corresponds to a specific character in the encrypted output.

This class of ciphers is further categorized based on how the substitution is applied throughout
the message. A monoalphabetic substitution cipher uses a single, fixed substitution alphabet
for the entire message. This means that every instance of a specific letter, say 'E', is always
replaced by the same ciphertext letter, like 'X', regardless of where it appears in the message.
This simplicity is its most significant weakness, as it preserves the frequency distribution of
letters from the original language.

Example 3:

Baconian Cipher

Objective:

Implement a Baconian Cipher, encoding letters as 5-bit binary codes disguised as two-letter
combinations (A/B).Tools: PythonTasks:

Create a Baconian code mapping.

Implement encryption to produce A/B sequences.

Test with sample plaintext.


Sample Code:

def baconian_encrypt(plaintext):

bacon_codes = {

'A': 'AAAAA', 'B': 'AAAAB', 'C': 'AAABA', 'D': 'AAABB', 'E': 'AABAA',

'F': 'AABAB', 'G': 'AABBA', 'H': 'AABBB', 'I': 'ABAAA', 'J': 'ABAAA',

'K': 'ABAAB', 'L': 'ABABA', 'M': 'ABABB', 'N': 'ABBAA', 'O': 'ABBAB',

'P': 'ABBBA', 'Q': 'ABBBB', 'R': 'BAAAA', 'S': 'BAAAB', 'T': 'BAABA',

'U': 'BAABB', 'V': 'BAABB', 'W': 'BABAA', 'X': 'BABAB', 'Y': 'BABBA', 'Z': 'BABBB'

plaintext = plaintext.upper().replace(" ", "")

ciphertext = ""

for char in plaintext:

if char.isalpha():

ciphertext += bacon_codes[char] + " "

else:

ciphertext += char + " "

return ciphertext.strip()

# Example usage

plaintext = "BACON"

ciphertext = baconian_encrypt(plaintext)

print(f"Plaintext: {plaintext}")
print(f"Ciphertext: {ciphertext}")

Sample Output:

Plaintext: BACON

Ciphertext: AAAAB AAABA ABBAB AABAA ABBAA

Explanation: The Baconian Cipher encodes letters as 5-bit A/B sequences, differing from
substitution ciphers in prior examples by using a binary-like representation, historically used for
hidden messages.

In contrast, a polyalphabetic substitution cipher uses multiple substitution alphabets, often


shifting which alphabet is used at each position in the message. This makes it far more resistant
to cryptanalytic techniques like frequency analysis.

The security of a substitution cipher is directly related to the size of its key space. A general
substitution cipher on the 26-letter English alphabet has a massive number of possible
arrangements, specifically 26 factorial (26!), which is a number over 403 quintillion. This
immense key space makes a brute-force attack on a general substitution cipher computationally
infeasible.

5.2 The Caesar Cipher: A Classic Case Study

Named after Julius Caesar, who used it for military correspondence, the Caesar cipher is one of
the simplest and most widely known encryption techniques. It is a specific type of
monoalphabetic substitution cipher where each letter is replaced by a letter a fixed number of
positions down the alphabet. The key is simply the number of positions to shift. For example,
with a shift of 5, the plaintext message "hello" becomes the ciphertext "mjqqt".

The mechanics of the Caesar cipher are elegantly described using modular arithmetic. By first
mapping each letter to a number (A=0, B=1,..., Z=25), the encryption process can be defined by
the following mathematical formula :

En(x)=(x+n)mod26

Here, x is the numerical value of the plaintext letter, n is the shift value (the key), and En(x) is
the numerical value of the resulting ciphertext letter. The modulo operator ensures that the result
wraps around to the beginning of the alphabet when the shift goes beyond 'Z'. Decryption is
performed by a similar reversal:
Dn(x)=(x−n)mod26

Table A.3: Alphabet to Numeric Mapping

Letter A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Value 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
Export to Sheets

Table A.4: Caesar Cipher Example

Plaintext THE QUICK BROWN FOX


Shift Value 3 (Key)
Ciphertext QEB NRFZH YOLTK CLU

The inherent simplicity of the Caesar cipher is its ultimate downfall. Its fixed, monoalphabetic
substitution means that the statistical distribution of letters in the plaintext is perfectly preserved
in the ciphertext. For a cryptanalyst, this means that the most frequent letter in the ciphertext will
almost certainly correspond to the most frequent letter in the English language (which is 'E').
This vulnerability to frequency analysis, combined with a minuscule key space of only 25
possible shifts, makes the Caesar cipher completely insecure against a brute-force attack.

6: Implementing Substitution and Caesar Ciphers: Python


Implementations
6.1 Implementing a Simple Substitution Cipher

The most basic way to implement a substitution cipher is by using a dictionary to map each letter
of the plaintext alphabet to its corresponding letter in a randomly scrambled alphabet. The
inverse of this dictionary is then used for decryption.

Example 6.1.1: A Basic Dictionary-Based Substitution Cipher

A substitution cipher can be implemented in Python using a simple dictionary to map each
plaintext character to its ciphertext equivalent.

Python
# A simple, manually-defined substitution key
# Note: A secure key should be a random permutation of the alphabet.
SUBSTITUTION_KEY = {
'a': 'm', 'b': 'n', 'c': 'b', 'd': 'v', 'e': 'c', 'f': 'x', 'g': 'z',
'h': 'a', 'i': 's', 'j': 'd', 'k': 'f', 'l': 'g', 'm': 'h', 'n': 'j',
'o': 'k', 'p': 'l', 'q': 'p', 'r': 'o', 's': 'i', 't': 'u', 'u': 'y',
'v': 't', 'w': 'r', 'x': 'e', 'y': 'w', 'z': 'q'
}

def encrypt_substitution(message, key):


encrypted_message = ""
for char in message.lower():
encrypted_message += key.get(char, char)
return encrypted_message

# Encrypt a simple message


plaintext = "hello world"
ciphertext = encrypt_substitution(plaintext, SUBSTITUTION_KEY)
print(f"Plaintext: {plaintext}")
print(f"Ciphertext: {ciphertext}")

6.2 Implementing the Caesar Cipher

The Caesar cipher is a specific type of substitution cipher where the key is just a number
representing the shift. This makes its implementation particularly straightforward.

Example 6.2.1: Encrypting with the Caesar Cipher

This function implements the Caesar cipher using the principles of modular arithmetic. It handles
both uppercase and lowercase letters and leaves non-alphabetic characters unchanged.

Python
def caesar_encrypt(text, shift):
result = ""
for char in text:
if 'a' <= char <= 'z':
start = ord('a')
result += chr((ord(char) - start + shift) % 26 + start)
elif 'A' <= char <= 'Z':
start = ord('A')
result += chr((ord(char) - start + shift) % 26 + start)
else:
result += char
return result

plaintext = "Hello, Caesar Cipher!"


shift = 3
encrypted_text = caesar_encrypt(plaintext, shift)
print(f"Plaintext: {plaintext}")
print(f"Shift: {shift}")
print(f"Ciphertext: {encrypted_text}")

Example 6.2.2: Decrypting the Caesar Cipher

The beauty of a symmetric cipher is that decryption can be performed by simply applying the
inverse operation. For the Caesar cipher, this means applying a negative shift of the same
magnitude.

Python
def caesar_decrypt(text, shift):
# Decryption is simply encryption with a negative shift
return caesar_encrypt(text, -shift)

ciphertext = "Khoor, Fdhvdu Flskhu!"


shift = 3
decrypted_text = caesar_decrypt(ciphertext, shift)
print(f"Ciphertext: {ciphertext}")
print(f"Shift: {shift}")
print(f"Decrypted: {decrypted_text}")

Conclusions

The analysis of classical encryption techniques, from the foundational Symmetric Cipher Model
to the specific implementation of the Caesar cipher, provides a critical understanding of both the
principles of cryptography and the methods used for cryptanalysis. The report demonstrates that
the security of a cryptographic system is fundamentally tied to the size of its key space and the
complexity of its underlying algorithm. The Caesar cipher, with its small key space and
monoalphabetic design, serves as a powerful example of a system inherently vulnerable to
simple cryptanalytic attacks.

You might also like