#!/usr/bin/env python3
"""Generate RSA challenge with small public exponent e=3"""
from Crypto.PublicKey import RSA
from Crypto.Util.number import bytes_to_long, long_to_bytes
import json
import os

FLAG = os.environ.get('FLAG', 'FLAG{rsa_small_exponent_cube_root_attack}')

# Generate a large RSA key
key = RSA.generate(2048)
n = key.n
e = 3  # VULNERABLE: small exponent

# Encrypt the flag
m = bytes_to_long(FLAG.encode())
c = pow(m, e, n)

# Since e=3 and the message is short relative to n,
# m^3 < n, so c = m^3 (no modular reduction!)
# This means we can just take the cube root of c

challenge_data = {
    'n': str(n),
    'e': e,
    'c': str(c),
    'hint': 'The public exponent is very small. Think about what happens when m^e < n.',
    'algorithm': 'RSA',
    'key_size': 2048
}

with open('/app/challenge/rsa_challenge.json', 'w') as f:
    json.dump(challenge_data, f, indent=2)

print(f"RSA challenge generated")
print(f"n = {n}")
print(f"e = {e}")
print(f"c = {c}")
print(f"m^e < n? {pow(m, e) < n}")
print(f"Flag length: {len(FLAG)} chars")
