#!/usr/bin/env python3

from Cryptotools.Numbers.coprime import phi
from Cryptotools.Utils.utils import gcd

def generate_keys():
    p = 7853
    q = 7919
    n = p * q
    e  = 65536 # It's public value, must be coprime with phi n
    
    print(n)
    #phin = phi(n)
    phin = (p - 1) * (q - 1)
    print(phin)
    
    for _ in range(2, phin):
        if gcd(phin, e) == 1:
            break
        e += 1
    
    print(e)
    plaintext = 'A'
    ciphertext = pow(ord(plaintext), e, n)
    print(f"Ciphertext: {ciphertext}")

# Now, we can test

# To resolve that formula: C = x ** e mod n
# Where C is the ciphertext, and C, e and n are known (public values)
# First, we need to find the reverse modular of phi(n) or carmi(n)
# z = e -1 mod phi(n)
# After that, we have our decryption key, we can resolve x
# x = C ** z mod n
# The RSA Problem is to decrypt with the public-key
# We just need to find the decryption key with the public-key and the modulus

# First, we need to find phi(n)
# phin = phi(n) # I computed here, result = 62172136

n = 62187907
phin = 62172136
e = 65537
ciphertext = 38605768
# print(phin)

# Find the reverse modular
d = pow(e, -1, phin)
# print(d)
plaintext = pow(ciphertext, d, n)
print(chr(plaintext))

