def facto_fermat(n, verbose=False): """Fermat's factoring algorithm. Args: - *n (int)*: an odd integer Optional Args: - *verbose (bool)*: set to True if you want a display. Returns: - *(int)*: a subfactor of n. Not very efficient. """ if(n%2 == 0): print("facto_fermat error: n even") return 0 aux = itools.isqrt(n) if aux*aux == n: if(verbose): print("n is a square") aux += 1 res = aux*aux - n if(verbose): print(res) r = itools.isqrt(res) e = r*r - res while(e != 0): aux += 1 res = aux*aux - n r = itools.isqrt(res) e = r*r - res res = aux + itools.isqrt(res) if(vernose): print("facto_fermat :\n",n,"=",res,"*",n//res) return res
def weger1(n,e,m,c,verbose=False): """Trivial implementation of Weger's attack on RSA that uses a plain and a cipher to test potential private exponents. Args: - *n (int)*: the modulo - *e (int)*: public exponent - *m (int)*: plain - *c (int)*: cypher (m^e % n) Optional Args: - *verbose (bool)*: set to True to get a display. Returns: - *(int)*: the private exponent if the attack succeeded 0 if attack failed For this attack to work, the private exponent d must be such that : d < (n^(3/4))/abs(p-q) p and q must close to each other. d is then the denominator of a reduced fraction of e/(n+1-2*sqrt(n)) : In this attack we assume Phi(n) ~ (n+1-2*sqrt(n)) (since we assume p ~ q ~ sqrt(n)) """ conv = gen_convergents(n+1-2*itools.isqrt(n), e) for d in conv: if(verbose): print("d prob =",d) p = itools.exp_mod(c,d,n) if(verbose): print("pow =",p) if p == m%n: if(verbose): print("\nweger : success!!!\nSecret exponent :", d, "\n") return d if(verbose): print("\nweger failed :(\n") return 0
def weger2(n,e,verbose=False): """Trivial implementation of Weger's attack on RSA which computes Phi(n) to test potential private exponents. Args: - *n (int)*: the modulo - *e (int)*: public exponent Optional Args: - *verbose (bool)*: set to True to get a display. Returns: - *(int)*: the private exponent if the attack succeeded 0 if attack failed For this attack to work, the private exponent d must be such that : d < (n^(3/4))/abs(p-q) p and q must close to each other. d is then the denominator of a reduced fraction of e/(n+1-2*sqrt(n)) : In this attack we assume Phi(n) ~ (n+1-2*sqrt(n)) (since we assume p ~ q ~ sqrt(n)) """ conv = gen_convergents(n+1-2*itools.isqrt(n), e, False, False) for f in conv: k = f[0] d = f[1] if (k!=0): t = (e*d-1) % k if(t==0): if(verbose):print("d prob :",d) phi = (e*d-1)//k p,q = get_pq(n,phi,verbose) if(verbose): print("p,q prob:", p, q) if(int(p)*int(q) == n): if(verbose): print("\nweger : success!!!\nSecret exponent :", d, "\n") return d if(verbose): print("\nweger failed :(\n")