Cyber Python Practical File
Cyber Python Practical File
Python code:
import sqlite3
from cryptography.fernet import Fernet
key = Fernet.generate_key()
cipher_suite = Fernet(key)
conn = sqlite3.connect('user_data.db')
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL,
password TEXT NOT NULL
)
''')
conn.commit()
# Example usage
add_user('alice', 'alice_password')
add_user('bob', 'bob_password')
# Function to retrieve and print users with encrypted passwords
def print_encrypted_users():
cursor.execute('SELECT * FROM users')
rows = cursor.fetchall()
Server
import socket
import ssl
while True:
client_socket, client_address = sock.accept()
print(f"Connection from {client_address}")
try:
data = ssl_client_socket.recv(1024)
print(f"Received: {data.decode()}")
ssl_client_socket.sendall(b"Hello, SSL client!")
finally:
ssl_client_socket.close()
create_ssl_server('localhost', 8080)
Client
import socket
import ssl
Make sure OpenSSL is installed on your system. You can check this by running:
openssl>version
You'll be prompted to enter information such as country, state, organization, and common
name (the domain name or IP address).
Step 4: Generate a Self-Signed Certificate
Finally, create the self-signed certificate using the CSR and the private key:
This command generates a self-signed certificate valid for 365 days and saves it as
self_signed_certificate.pem.
bash
Copy code
openssl>x509 -in self_signed_certificate.pem -text -noout
python ssl_server.py
MIME (Multipurpose Internet Mail Extensions) is a standard used to extend the format of
email messages to support text in character sets other than ASCII, as well as attachments of
audio, video, images, and application programs.
MIME is essential for modern email communication, enabling rich content and diverse media
types. It’s widely used in email clients, web applications, and APIs to facilitate sending and
receiving complex messages.
● The term "opaque" refers to a signature that is not directly interpretable or visible in
its content.
● An opaque signature hides the specific details of the signed content. This means that
the signature itself does not reveal any information about the content it is signing,
which enhances security.
● When a message is signed with an opaque signature, the recipient can verify that the
message hasn't been altered since it was signed. However, the signature doesn't
provide insights into what the original message contains beyond confirming its
integrity.
● The primary goal of an opaque signature is to ensure that the recipient can validate
the authenticity of the message without needing to understand the signature's inner
workings or exposing the original content.
mime.py
import base64
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import rsa, padding
public_key = private_key.public_key()
return msg
def sign_message(message):
"""Signs the MIME message and returns the signature."""
message_bytes = message.as_bytes()
signature = private_key.sign(
message_bytes,
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
)
return base64.b64encode(signature).decode('utf-8')
To verify the signature, you can use the public key and compare the signature against the
original message:
try:
public_key.verify(
signature_bytes,
message_bytes,
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
)
return True
except Exception as e:
print(f"Verification failed: {e}")
return False
Explanation:
The code demonstrates how to create a MIME message, digitally sign it, and attach the
signature as a separate part.
The use of cryptography ensures the integrity and authenticity of the message.
This approach is useful in scenarios where you need to ensure that the message has not
been altered and comes from a legitimate sender.
import base64
from email.mime.text import MIMEText
base64: This module is used for encoding binary data into ASCII text, making it suitable for
transmission.
email.mime: These classes help create and manipulate MIME messages. MIMEText is for
plain text, and MIMEMultipart is for messages that may contain multiple parts.
cryptography: This library provides tools for encryption, hashing, and digital signatures. The
specific components used here include:
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend()
public_key = private_key.public_key()
Here, we generate an RSA private key.
The public_exponent is typically set to 65537, which is a common choice for security and
performance.
The key_size of 2048 bits is a good balance of security for most applications.
The public_key method retrieves the corresponding public key for later verification.
The public exponent is part of the mathematical operations used to encrypt data and verify
signatures.
Other values like 3 or 17 are sometimes used, but they have certain security considerations.
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = "[email protected]"
msg['To'] = "[email protected]"
msg.attach(text_part)
return msg
This function constructs a MIME message:
def sign_message(message):
message_bytes = message.as_bytes()
signature = private_key.sign(
message_bytes,
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
return base64.b64encode(signature).decode('utf-8')
The resulting signature is encoded in Base64 for easy transmission and returned as a string.
signature = sign_message(mime_message)
print("MIME Message:")
print(mime_message.as_string())
print(signature)
Here, we set the subject and body for the email, create the MIME message using
create_mime_message, and sign it with sign_message.
message_bytes = message.as_bytes()
signature_bytes = base64.b64decode(signature)
try:
public_key.verify(
signature_bytes,
message_bytes,
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
return True
except Exception as e:
return False
If the verification passes, it returns True; otherwise, it catches the exception and prints an
error message.