KINGDOM OF SAUDI ARABIA المملكة العربية السعودية
MINISTRY OF EDUCATION – JAZAN UNIVERSITY جــامـعــة جـــــازان- وزارة التعليم
COLLEGE OF ENGINEERING & COMPUTER SCIENCE كلية الهندسة وعلوم الحاسب
FINAL LAB EXAM
BACHELOR IN INFORMATION TECHNOLOGY
Academic Year: 2024 – 2025 Term: ( First / Second)
Student Name: Student ID:
Section Number: 12396 Start Date: 15-05-2025, 10 AM
Course Name: Cryptography & Data Security End Date: 15-05-2025, 12 PM
Course Code: ITEC-332 Course Level: 6 Total Marks: 10
Marks Summary (10)
Question # Performance Indicator Total Marks Obtained Marks
Q.1 PI – (2.3) 5
Q.2 PI – (2.4) 5
Teacher’s Signature 10
CLO-PI-SO Mapping
CLO IDs SO-1 SO-2 SO-3 SO-4 SO-5 SO-6
CLO#01 PI 1.1 - - - - -
CLO#02 PI 1.2 - - - - -
CLO#03 PI 1.3 - - - - -
CLO#04 - PI 2.2 - - - -
CLO#05 - PI 2.3, PI 2.4 - - - PI 6.3
CLO#06 - - - - - PI 6.1
INSTRUCTIONS FOR STUDENTS
1. Solve all the questions. The questions are based on the lab exercises mentioned in the lab manual.
2. Complete the assignments within due time and upload your assignment (.py, and .pdf separately for
each program) to the blackboard.
3. Make sure your assignment is submitted completely on Blackboard systems by the deadline.
4. Late submission will reduce your marks.
5. No submission will be entertained on WhatsApp or by mail.
6. Any Cheating or Copying of other assignments will be strictly dealt with. Your work will be checked
for plagiarism using the plagiarism check software in Blackboard, and marks will be deducted.
تعليمات للطالب
األسئلة مبنية على تمارين المختبر المذكورة في دليل المختبر.حل جميع األسئلة.1
ملفات( أكمل الواجبات في الوقت المحدد وقم بتحميل واجبك.py و.pdf على السبورة )بشكل منفصل لكل برنامج.2
تأكد من تقديم واجبك بالكامل على أنظمة بالك بورد قبل الموعد النهائي.3
سيؤدي التأخر في التسليم إلى تقليل درجاتك.4
لن يتم قبول أي تقديم علىWhatsApp أو عن طريق البريد.5
وسيتم خصم، سيتم فحص عملك بحثًا عن االنتحال باستخدام برنامج فحص االنتحال في بالك بورد.سيتم التعامل بصرامة مع أي غش أو نسخ لمهام أخرى
الدرجات.6
ITEC-332/Cryptography & Data Security/2024-2025/Second Semester Page 1 of
10
Marks Allotted Marks Obtained
Question - 1 PI 2.3
05
Answer All the questions.
Ali is working on securing a communication channel for an e-commerce website to ensure confidential
transactions between users and the platform. He decides to implement the RSA encryption algorithm
to protect sensitive data.
Requirements:
▪ Write a Python script to generate RSA key pairs (public and private keys) using appropriate
prime numbers.
▪ Develop a function to encrypt a plaintext message using the RSA public key.
▪ Implement a function to decrypt the ciphertext using the RSA private key.
Deliverables:
▪ A well-commented script for RSA key generation, encryption, decryption, and signature
verification.
▪ Detailed explanation of RSA implementation steps.
▪ Testcases demonstrating encryption, decryption for RSA algorithm.
Answer:
import random # Used for generating random prime numbers and keys
def is_prime(n):
# Checks if a number is prime (for selecting p and q in RSA)
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1): # Check divisibility up to square root of n
if n % i == 0:
return False
return True
def gcd(a, b):
# Computes Greatest Common Divisor using Euclidean algorithm
while b:
a, b = b, a % b # Swap and reduce until b becomes zero
return a
def mod_inverse(e, phi):
# Finds modular multiplicative inverse d such that (d * e) % phi == 1
d=1
while (d * e) % phi != 1: # Brute-force approach to find d
ITEC-332/Cryptography & Data Security/2024-2025/Second Semester Page 2 of
10
d += 1
return d
def generate_rsa_keys():
# Step 1: Choose two distinct large primes p and q
p = random.choice([x for x in range(100, 300) if is_prime(x)])
q = random.choice([x for x in range(100, 300) if is_prime(x)])
n = p * q # Compute modulus n used in both public and private keys
phi = (p - 1) * (q - 1) # Euler's totient function φ(n)
# Step 2: Choose public exponent e such that 1 < e < phi and coprime with phi
e = random.randint(2, phi - 1)
while gcd(e, phi) != 1: # Ensure e and phi are coprime
e = random.randint(2, phi - 1)
# Step 3: Compute private exponent d
d = mod_inverse(e, phi)
# Return public key (e, n) and private key (d, n)
return ((e, n), (d, n))
def rsa_encrypt(public_key, plaintext):
# Encrypts message by raising each character’s ASCII value to power e mod n
e, n = public_key
ciphertext = [pow(ord(char), e, n) for char in plaintext]
return ciphertext
def rsa_decrypt(private_key, ciphertext):
# Decrypts message by raising each cipher value to power d mod n
d, n = private_key
plaintext = ''.join([chr(pow(char, d, n)) for char in ciphertext])
return plaintext
# Test Case
public_key, private_key = generate_rsa_keys()
message = "HelloRSA"
ciphertext = rsa_encrypt(public_key, message)
decrypted_message = rsa_decrypt(private_key, ciphertext)
# Output results
print("Public Key:", public_key)
print("Private Key:", private_key)
print("Plaintext:", message)
print("Ciphertext:", ciphertext)
print("Decrypted Text:", decrypted_message)
ITEC-332/Cryptography & Data Security/2024-2025/Second Semester Page 3 of
10
Overview
The script performs the following tasks:
Generates two large prime numbers.
Computes the RSA public and private keys.
Implements encryption using the public key.
Implements decryption using the private key.
Tests the system by encrypting and decrypting a sample message.
Function: `is_prime(n)`
This function checks whether a given number `n` is a prime number. It does so by testing divisibility up
to the square root of `n`. This is used to select the two large primes `p` and `q` needed in RSA.
Function: `gcd(a, b)`
This computes the greatest common divisor (GCD) of two numbers using the Euclidean Algorithm. It
helps ensure that the public exponent `e` is relatively prime (coprime) to Euler's totient value `φ(n)`.
Function: `mod_inverse(e, phi)`
This finds the modular multiplicative inverse of `e` modulo `phi`. The result is the private key exponent
`d`, such that:
```
(d e) ≡ 1 mod φ
```
This ensures that encryption and decryption are inverses of each other.
Function: `generate_rsa_keys()`
This function follows the standard steps of RSA key generation:
1. Selects two distinct random prime numbers `p` and `q`.
2. Calculates `n = p q`, which becomes part of both the public and private keys.
3. Computes `φ(n) = (p 1) (q 1)`, known as Euler’s totient function.
4. Chooses a public exponent `e` such that:
`1 < e < φ(n)`
ITEC-332/Cryptography & Data Security/2024-2025/Second Semester Page 4 of
10
`gcd(e, φ(n)) == 1` (i.e., `e` and `φ(n)` are coprime)
5. Computes the private exponent `d` using modular inverse so that:
`(d e) % φ(n) == 1`
6. Returns the public key `(e, n)` and private key `(d, n)`.
Function: `rsa_encrypt(public_key, plaintext)`
This function takes a message (string) and the public key `(e, n)` to perform encryption.
Each character in the message is converted into its ASCII value using `ord()`.
That value is then raised to the power of `e` modulo `n` using the `pow()` function for secure modular
exponentiation.
The output is a list of integers representing the encrypted message.
Function: `rsa_decrypt(private_key, ciphertext)`
This function takes the encrypted message (a list of integers) and the private key `(d, n)` to perform
decryption.
Each integer in the ciphertext is raised to the power of `d` modulo `n`.
The resulting number is converted back into a character using `chr()`.
These characters are joined into a string representing the original message.
Test Case
A test case is included to demonstrate the full process:
1. Generate a new RSA key pair.
2. Define a sample message like `"HelloRSA"`.
3. Encrypt the message using the public key.
4. Decrypt the resulting ciphertext using the private key.
5. Print out the keys, plaintext, ciphertext, and decrypted text to verify correctness.
ITEC-332/Cryptography & Data Security/2024-2025/Second Semester Page 5 of
10
ITEC-332/Cryptography & Data Security/2024-2025/Second Semester Page 6 of
10
Marks Allotted Marks Obtained
Question - 2 PI 2.4
05
Answer All the questions.
Ahmad is developing a secure messaging application that enables two users to establish a shared secret key without
directly transmitting it. He decides to implement the Diffie-Hellman Key Exchange Algorithm in Python to
securely exchange encryption keys between users. The goal is to protect sensitive communications from
eavesdroppers.
Requirements:
▪ Write a Python script to generate private and public keys for two users using random values and predefined
parameters (prime number p and primitive root g).
▪ Simulate the exchange of public keys between two communicating parties.
Deliverables:
▪ A script demonstrating Diffie-Hellman key exchange and integration with encryption.
▪ Explanation of mathematical concepts, implementation details, and key exchange workflow.
▪ Testcases show key generation, key exchange, and encryption/decryption.
▪ Discussion on potential attacks and mitigation strategies for secure key exchange.
Answer:
import random # For choosing private keys
def diffie_hellman_key_exchange():
# Publicly agreed values
p = 23 # A small prime number (in real use, this should be very large)
g = 5 # Primitive root modulo p
# Each party selects a private key randomly
a = random.randint(1, p - 1) # Alice's private key
b = random.randint(1, p - 1) # Bob's private key
# Generate public keys using modular exponentiation
A_pub = pow(g, a, p) # Alice computes A = g^a mod p
B_pub = pow(g, b, p) # Bob computes B = g^b mod p
# Exchange public keys and compute shared secret
s_Alice = pow(B_pub, a, p) # Alice computes S = B^a mod p
s_Bob = pow(A_pub, b, p) # Bob computes S = A^b mod p
# Return all values including computed shared secrets
return {
'p': p,
'g': g,
'Alice_private': a,
'Bob_private': b,
'Alice_public': A_pub,
'Bob_public': B_pub,
'Shared_secret_Alice': s_Alice,
'Shared_secret_Bob': s_Bob
}
ITEC-332/Cryptography & Data Security/2024-2025/Second Semester Page 7 of
10
# Run test case
result = diffie_hellman_key_exchange()
# Print results for verification
print("Prime (p):", result['p'])
print("Primitive Root (g):", result['g'])
print("Alice's Private Key:", result['Alice_private'])
print("Bob's Private Key:", result['Bob_private'])
print("Alice's Public Key:", result['Alice_public'])
print("Bob's Public Key:", result['Bob_public'])
print("Shared Secret (Alice):", result['Shared_secret_Alice'])
print("Shared Secret (Bob):", result['Shared_secret_Bob'])
print("Do secrets match?", result['Shared_secret_Alice'] == result['Shared_secret_Bob'])
Purpose
The goal of this script is to simulate how two users (commonly referred to as Alice and Bob) can generate a shared
secret key without ever directly transmitting it. This key can later be used for symmetric encryption like AES.
Public Parameters
Two values are publicly agreed upon by both parties:
`p`: A prime number — in this example, it's set to 23. In realworld applications, this should be a very large prime.
`g`: A primitive root modulo `p` — here, it's set to 5. This ensures that all possible residues modulo `p` can be
generated using powers of `g`.
These values are known to everyone, including potential eavesdroppers.
Private Keys
Each party chooses a private key randomly:
Alice selects a private key `a`, which is a random integer between 1 and `p 1`.
Bob selects a private key `b`, also within the same range.
These private keys are kept secret and never transmitted.
Public Key Generation
Using their private keys, each user generates a public key based on the agreedupon values `g` and `p`:
Alice computes:
`A_pub = g^a mod p`
Bob computes:
`B_pub = g^b mod p`
These public keys are exchanged between Alice and Bob over the communication channel.
ITEC-332/Cryptography & Data Security/2024-2025/Second Semester Page 8 of
10
Shared Secret Calculation
After exchanging public keys:
Alice uses Bob’s public key to compute the shared secret:
`s_Alice = B_pub^a mod p`
Bob uses Alice’s public key to compute the shared secret:
`s_Bob = A_pub^b mod p`
Due to the properties of modular exponentiation, these two computed values are mathematically equal:
```
(g^b)^a mod p = (g^a)^b mod p
```
So, both parties now have the same shared secret key, even though they never directly sent it to each other.
Return Values
The function returns a dictionary containing:
The public parameters `p` and `g`
Each user's private and public keys
The shared secret calculated by each party
This allows verification that both parties arrived at the same secret.
Test Case Execution
The script runs the DiffieHellman function and prints out all the generated values for inspection:
Displays the chosen prime `p` and primitive root `g`
Shows each user's private and public keys
Prints the shared secrets from both Alice and Bob
Confirms whether both shared secrets match
This confirms that the key exchange worked correctly.
ITEC-332/Cryptography & Data Security/2024-2025/Second Semester Page 9 of
10
ITEC-332/Cryptography & Data Security/2024-2025/Second Semester Page 10 of
10