1.
Develop a simple client and server application using SSL socket communication
If you want to know the port number and IP address
import socket
# Create a TCP socket
s = [Link](socket.AF_INET, socket.SOCK_STREAM)
# Bind to any available port
[Link](('[Link]', 0))
# Get the assigned IP and port
ip, port = [Link]()
print(f"My IP: {ip}")
print(f"My Port: {port}")
[Link]()
Program
import threading
import time
import socket
import ssl
import tempfile
import os
from cryptography import x509
from [Link] import NameOID
from [Link] import hashes
from [Link] import rsa
from [Link] import serialization
from datetime import datetime, timedelta
def generate_self_signed_cert():
# Generate a private key
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
)
# Generate a self-signed certificate
subject = issuer = [Link]([
[Link](NameOID.COUNTRY_NAME, u"IN"),
[Link](NameOID.STATE_OR_PROVINCE_NAME, u"Tamil
Nadu"),
[Link](NameOID.LOCALITY_NAME, u"Vellore"),
[Link](NameOID.ORGANIZATION_NAME, u"VIT"),
[Link](NameOID.COMMON_NAME, u"localhost"),
])
cert = [Link]().subject_name(
subject
).issuer_name(
issuer
).public_key(
private_key.public_key()
).serial_number(
x509.random_serial_number()
).not_valid_before(
[Link]()
).not_valid_after(
[Link]() + timedelta(days=10)
).add_extension(
[Link]([[Link](u"localhost")]),
critical=False,
).sign(private_key, hashes.SHA256())
# Write the certificate and private key to temporary files
cert_file = [Link](delete=False, suffix='.pem')
key_file = [Link](delete=False, suffix='.pem')
cert_file.write(cert.public_bytes([Link]))
key_file.write(private_key.private_bytes(
encoding=[Link],
format=[Link],
encryption_algorithm=[Link]()
))
cert_file.close()
key_file.close()
return cert_file.name, key_file.name
def run_server(cert_path, key_path):
HOST, PORT = '[Link]', 51992
ssl_context = [Link](ssl.PROTOCOL_TLS_SERVER)
# Using the dynamically generated certificate and key
ssl_context.load_cert_chain(certfile=cert_path, keyfile=key_path)
with [Link](socket.AF_INET, socket.SOCK_STREAM, 0) as sock:
[Link]((HOST, PORT))
[Link](5)
print(f" Server listening on {HOST}:{PORT}")
conn, addr = [Link]()
with ssl_context.wrap_socket(conn, server_side=True) as ssl_conn:
print(f" Connection from {addr}")
data = ssl_conn.recv(1024).decode('utf-8')
print(f" Received: {data}")
ssl_conn.send(b"Hello from server!")
def run_client():
[Link](1) # Wait for server to start
HOST, PORT = '[Link]', 51992
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE # Don't verify the certificate for
testing
with socket.create_connection((HOST, PORT)) as sock:
with ssl_context.wrap_socket(sock, server_hostname=HOST) as ssock:
print(f" Connected: {[Link]()}")
[Link](b"Hello from client!")
data = [Link](1024)
print(f" Received: {[Link]()}")
# Generate certificate and key
cert_path, key_path = generate_self_signed_cert()
print(f"Generated temporary certificate at: {cert_path}")
print(f"Generated temporary key at: {key_path}")
# Run both server and client
server_thread = [Link](target=run_server, args=(cert_path, key_path))
client_thread = [Link](target=run_client)
try:
server_thread.start()
client_thread.start()
server_thread.join()
client_thread.join()
finally:
# Clean up temporary files
try:
[Link](cert_path)
[Link](key_path)
print("Temporary certificate and key files removed")
except:
pass
2. Develop a web application that implements JSON web token
Program
html
<!DOCTYPE html>
<html>
<head>
<title>JSON Data Example</title>
<style>
/* CSS for styling */
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
button {
background-color: #4CAF50;
color: white;
padding: 10px 15px;
border: none;
border-radius: 4px;
cursor: pointer;
margin-bottom: 20px;
}
#result {
border: 1px solid #ddd;
padding: 15px;
border-radius: 5px;
background-color: #f9f9f9;
}
.user-item {
margin-bottom: 10px;
padding: 10px;
background-color: #fff;
border-radius: 3px;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}
</style>
</head>
<body>
<h1>Fetch JSON Data Example</h1>
<button id="fetchBtn">Fetch Users Data</button>
<div id="result">
<p>Click the button to fetch data...</p>
</div>
<script>
// JavaScript to fetch JSON data
[Link]('fetchBtn').addEventListener('click', function() {
// Using the JSONPlaceholder API as an example
fetch('[Link]
.then(response => {
if (![Link]) {
throw new Error('Network response was not ok');
}
return [Link]();
})
.then(data => {
// Display the JSON data
const resultDiv = [Link]('result');
[Link] = '<h2>Users:</h2>';
[Link](user => {
const userDiv = [Link]('div');
[Link] = 'user-item';
[Link] = `
<h3>${[Link]}</h3>
<p>Email: ${[Link]}</p>
<p>Phone: ${[Link]}</p>
`;
[Link](userDiv);
});
})
.catch(error => {
[Link]('result').innerHTML = `
<p style="color: red;">Error: ${[Link]}</p>
`;
});
});
</script>
</body>
</html>