from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import hashes

# ---------------------------------------------------------
# 1. Generate a PUBLIC key and a PRIVATE key
# ---------------------------------------------------------
print("🔐 Generating keys...")

private_key = rsa.generate_private_key(
    public_exponent=65537,
    key_size=2048
)

public_key = private_key.public_key()

print("✔ Keys generated!")
print("   - Public key:  share with anyone")
print("   - Private key: KEEP SECRET\n")


# ---------------------------------------------------------
# 2. Encrypt a message using the PUBLIC key
# ---------------------------------------------------------
message = b"Hello High School Tech Team!"

print("📤 Encrypting message with the PUBLIC key...")
ciphertext = public_key.encrypt(
    message,
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA256()),
        algorithm=hashes.SHA256(),
        label=None
    )
)

print("✔ Message encrypted!")
print("Ciphertext (scrambled):")
print(ciphertext)
print()


# ---------------------------------------------------------
# 3. Decrypt using the PRIVATE key
# ---------------------------------------------------------
print("📥 Decrypting message with the PRIVATE key...")
plaintext = private_key.decrypt(
    ciphertext,
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA256()),
        algorithm=hashes.SHA256(),
        label=None
    )
)

print("✔ Message decrypted!")
print("Plaintext:")
print(plaintext.decode())
print()


# ---------------------------------------------------------
# 4. Show the “one‑way door” concept
# ---------------------------------------------------------
print("🚫 Trying to decrypt using the PUBLIC key (this will fail)...")

try:
    public_key.decrypt(
        ciphertext,
        padding.OAEP(
            mgf=padding.MGF1(algorithm=hashes.SHA256()),
            algorithm=hashes.SHA256(),
            label=None
        )
    )
except Exception as e:
    print("❌ Public key CANNOT decrypt!")
    print("Reason:", e)
    print("\nThis is the whole point of public‑key encryption:")
    print("➡ Anyone can encrypt using the PUBLIC key.")
    print("➡ ONLY the PRIVATE key holder can decrypt.\n")
