"""Essential 09 — textbook RSA for number-theory exercises only."""
import json
from pathlib import Path
from math import gcd
from lab04 import sqm,inverseMod

def rsa_numbers(p,q,e):
    if p==q or p<2 or q<2: raise ValueError('Distinct primes required; supplied fixtures are public')
    phi=(p-1)*(q-1)
    if not 1<e<phi or gcd(e,phi)!=1: raise ValueError('Invalid exponent')
    return p*q,inverseMod(e,phi)

if __name__=='__main__':
    n,d=rsa_numbers(31,67,7); c=sqm(12,7,n); assert (n,d,c)==(2077,283,1481) and sqm(c,d,n)==12
    fixture=json.loads((Path(__file__).resolve().parent.parent/'challenges'/'rsa-fixture.json').read_text())
    x,m=int(fixture['c1']),int(fixture['c2']); expected=int(fixture['expected'])
    assert sqm(x,x,m)==pow(x,x,m)==expected
    p,q=int(fixture['p']),int(fixture['q']); phi=(p-1)*(q-1); e=65537
    while gcd(e,phi)!=1: e+=2
    n,d=rsa_numbers(p,q,e); assert sqm(sqm(12345,e,n),d,n)==12345
    print('Small and public large-fixture RSA checks passed')
