chatgpt/letters/two-key-pairs.py

42 lines
1.8 KiB
Python
Executable File

#!/usr/bin/python3
import ecdsa
from cryptography.fernet import Fernet
# Generate a signing key pair for the server
server_signing_private_key = ecdsa.SigningKey.generate(curve=ecdsa.SECP256k1)
server_signing_public_key = server_signing_private_key.get_verifying_key()
# Generate an encryption key pair for the server
server_ecdh = ecdsa.ECDH(curve=ecdsa.SECP256k1)
server_encryption_private_key = server_ecdh.generate_private_key()
server_encryption_public_key = server_ecdh.public_key(server_encryption_private_key)
# Generate a signing key pair for the client
client_signing_private_key = ecdsa.SigningKey.generate(curve=ecdsa.SECP256k1)
client_signing_public_key = client_signing_private_key.get_verifying_key()
# Generate an encryption key pair for the client
client_ecdh = ecdsa.ECDH(curve=ecdsa.SECP256k1)
client_encryption_private_key = client_ecdh.generate_private_key()
client_encryption_public_key = client_encryption_private_key.public_key()
# Exchange public keys between the server and the client
server_shared_secret = server_encryption_private_key.exchange(client_encryption_public_key)
client_shared_secret = client_encryption_private_key.exchange(server_encryption_public_key)
# Use the shared secret to create a Fernet object for encrypting/decrypting messages
server_fernet = Fernet(server_shared_secret)
client_fernet = Fernet(client_shared_secret)
# Sign and encrypt a message from the server to the client
message = "Hello, client!"
signed_message = server_signing_private_key.sign(message.encode())
encrypted_message = server_fernet.encrypt(signed_message)
# Verify and decrypt the message on the client side
verified_message = client_signing_public_key.verify(encrypted_message, signed_message)
decrypted_message = client_fernet.decrypt(verified_message)
print(decrypted_message) # "Hello, client!"