0% found this document useful (0 votes)
17 views11 pages

LAB6

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views11 pages

LAB6

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

NETWORKING AND DATA SECURITY (COMP8677-2-R-2024S)

LAB ASSIGNMENT 5
PREETHA SIVAKUMAR 110127240 & NAZHATH NAFIZZA NAZEERUDDIN 110126014

Question 1: Use openssl to generate RSA public/private key. This will generate a
rsa instance (p, q, d, e, n) with p, q of 1024 bits and to prevent leaking the private
key, the output private.pem is encrypted by aes128 cipher with password you will
be prompted to provide. Now use the above command to generate a rsa private key
and save it in file private.pem. Then, extract the public key (e, n) in a file
public.pem: $ openssl rsa –in private.pem –pubout >public.pem

Display private key using $openssl rsa –in private.pem –text -noout
Display public key using $openssl rsa –in public.pem –pubin –text -noout

Question 2:
a) Encrypt messages using PKCS1_OAEP, which is an implementation of RSA. Use the key RsaKey
derived above to do the encryption. The functions are described as follow.
• Cipher=PKCS1_OAEP.new(RsaKey): o For the encryption, RsaKey is a public-key. Return an
encryption object Cipher.
• Cipher.encrypt(message): This returns ciphertext of message (byte string) under encryption
object Cipher.

Code Encrypt_RSA.py:
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
import binascii

# Generate RSA key pair


key = RSA.generate(2048)
private_key = key.export_key()
public_key = key.publickey().export_key()

# Save the keys to files


with open("private.pem", "wb") as priv_file:
priv_file.write(private_key)
with open("public.pem", "wb") as pub_file:
pub_file.write(public_key)

# Load the public key for encryption


recipient_key = RSA.import_key(open("public.pem").read())
cipher = PKCS1_OAEP.new(recipient_key)

# Message to be encrypted
message = b"PREETHA SIVAKUMAR 110127240"

# Encrypt the message


ciphertext = cipher.encrypt(message)

# Save the ciphertext to a file


with open("ciphertext.bin", "wb") as f:
f.write(ciphertext)

# Print the ciphertext in hex format


print(binascii.hexlify(ciphertext))
b) Decrypt the ciphertext in (a). The functions are described as follow.
• Cipher=PKCS1_OAEP.new(RsaKey): o For the decryption, RsaKey is a private-key. Return an
decryption object Cipher.
• Cipher.decrypt(ctxt): o This returns message=’your name and ID’ under decryption object
Cipher.

Code for decrypt_RSA.py:


from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP

# Load the private key for decryption


private_key = RSA.import_key(open("private.pem").read())
cipher = PKCS1_OAEP.new(private_key)

# Load the ciphertext from the file


with open("ciphertext.bin", "rb") as f:
ciphertext = f.read()

# Decrypt the message


decrypted_message = cipher.decrypt(ciphertext)

# Print the decrypted message


print("Decrypted message:", decrypted_message.decode())

Question 4:
In this problem, you will use Diffie-Hellman with authentication to protect the client-server
communication. Implement the following functionalities.
a. Create two files: TCP client and TCP server, capable to chat with each other using socket.
b. Client and Server execute Diffie-Hellman to generate a shared key and use sha256 to hash this
shared key to 32-byte secret sk. Diffie-Hellman uses parameters:
p=258224987808690858965591917200301187432970579282922351283065935654064762201
6841194629645353280137831435903171972747559779 g=2 Note: x, y in Diffie-Hellman can be
obtained with Crypto.Random.random.getrandbits(400); see
https://pycryptodome.readthedocs.io/en/latest/src/random/random.html if necessary.
c. Sender (Client or Server) uses sk as a secret key of AES to encrypt your chat message in (a).
This results in ciphertext C and computes tag=sha256(C). In (a), sender sends (C, tag), instead of
plain chat message.
d. At the receiver, when receiving (C, tag), verify whether tag=sha256(C) holds. If it fails, raise
exception; otherwise, use sk as the AES secret to decrypt C. This will recover your chat message.
Paste your client and server programs in your submission file. Print out sk, C, tag and decrypted
chat message in (d) for one chat message

Code for Server.py

import socket
from Crypto.Random import get_random_bytes
from Crypto.Random.random import getrandbits
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Hash import SHA256
from Crypto.Util import number

# Diffie-Hellman parameters
p=
2582249878086908589655919172003011874329705792829223512830659
356540647622016841194629645353280137831435903171972747559779
g=2

# Generate private key


y = getrandbits(400)
Y = pow(g, y, p)

# Create server socket


server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', 12345))
server_socket.listen(1)

print("Server listening on port 12345...")

conn, addr = server_socket.accept()


print(f"Connected by {addr}")

# Receive the client's public key


X = int(conn.recv(4096).decode())
# Send the public key to the client
conn.send(str(Y).encode())

# Compute the shared key


shared_key = pow(X, y, p)
sk = SHA256.new(str(shared_key).encode()).digest()

print("Shared Key (sk):", sk.hex())

def encrypt_message(message, sk):


cipher = AES.new(sk, AES.MODE_CBC)
ciphertext = cipher.encrypt(pad(message.encode(), AES.block_size))
return cipher.iv + ciphertext

def decrypt_message(ciphertext, sk):


iv = ciphertext[:AES.block_size]
cipher = AES.new(sk, AES.MODE_CBC, iv)
plaintext = unpad(cipher.decrypt(ciphertext[AES.block_size:]),
AES.block_size)
return plaintext.decode()

while True:
# Receive the message
response = conn.recv(4096)
if not response:
break

received_C = response[:-32]
received_tag = response[-32:]

# Verify the tag


if SHA256.new(received_C).digest() != received_tag:
raise Exception("Tag verification failed")

# Decrypt the message


decrypted_message = decrypt_message(received_C, sk)
print("Decrypted message:", decrypted_message)
# Respond back to client
message = input("Enter message: ")

# Encrypt the message


C = encrypt_message(message, sk)
tag = SHA256.new(C).digest()

# Send the encrypted message and tag


conn.send(C + tag)

conn.close()
server_socket.close()

Code for Client.py


import socket
from Crypto.Random import get_random_bytes
from Crypto.Random.random import getrandbits
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Hash import SHA256
from Crypto.Util import number

# Diffie-Hellman parameters
p=
2582249878086908589655919172003011874329705792829223512830659
356540647622016841194629645353280137831435903171972747559779
g=2

# Generate private key


x = getrandbits(400)
X = pow(g, x, p)

# Connect to the server


client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('localhost', 12345))

# Send the public key to the server


client_socket.send(str(X).encode())

# Receive the server's public key


Y = int(client_socket.recv(4096).decode())

# Compute the shared key


shared_key = pow(Y, x, p)
sk = SHA256.new(str(shared_key).encode()).digest()

print("Shared Key (sk):", sk.hex())

def encrypt_message(message, sk):


cipher = AES.new(sk, AES.MODE_CBC)
ciphertext = cipher.encrypt(pad(message.encode(), AES.block_size))
return cipher.iv + ciphertext

def decrypt_message(ciphertext, sk):


iv = ciphertext[:AES.block_size]
cipher = AES.new(sk, AES.MODE_CBC, iv)
plaintext = unpad(cipher.decrypt(ciphertext[AES.block_size:]),
AES.block_size)
return plaintext.decode()

while True:
# Get user input
message = input("Enter message: ")

# Encrypt the message


C = encrypt_message(message, sk)
tag = SHA256.new(C).digest()

# Send the encrypted message and tag


client_socket.send(C + tag)

# Receive the response


response = client_socket.recv(4096)
if not response:
break

received_C = response[:-32]
received_tag = response[-32:]

# Verify the tag


if SHA256.new(received_C).digest() != received_tag:
raise Exception("Tag verification failed")

# Decrypt the message


decrypted_message = decrypt_message(received_C, sk)
print("Decrypted message:", decrypted_message)

client_socket.close()
Server Terminal:

Client Terminal:

You might also like