You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

64 lines
1.5 KiB

6 years ago
  1. '''
  2. Created on Dec 14, 2011
  3. @author: pablocelayes
  4. '''
  5. import ContinuedFractions, Arithmetic, RSAvulnerableKeyGenerator
  6. def hack_RSA(e,n):
  7. '''
  8. Finds d knowing (e,n)
  9. applying the Wiener continued fraction attack
  10. '''
  11. frac = ContinuedFractions.rational_to_contfrac(e, n)
  12. convergents = ContinuedFractions.convergents_from_contfrac(frac)
  13. for (k,d) in convergents:
  14. #check if d is actually the key
  15. if k!=0 and (e*d-1)%k == 0:
  16. phi = (e*d-1)//k
  17. s = n - phi + 1
  18. # check if the equation x^2 - s*x + n = 0
  19. # has integer roots
  20. discr = s*s - 4*n
  21. if(discr>=0):
  22. t = Arithmetic.is_perfect_square(discr)
  23. if t!=-1 and (s+t)%2==0:
  24. #print("Hacked!")
  25. return d
  26. # TEST functions
  27. def test_hack_RSA():
  28. print("Testing Wiener Attack")
  29. times = 5
  30. while(times>0):
  31. e,n,d = RSAvulnerableKeyGenerator.generateKeys(1024)
  32. print("(e,n) is (", e, ", ", n, ")")
  33. print("d = ", d)
  34. hacked_d = hack_RSA(e, n)
  35. if d == hacked_d:
  36. print("Hack WORKED!")
  37. else:
  38. print("Hack FAILED")
  39. print("d = ", d, ", hacked_d = ", hacked_d)
  40. print("-------------------------")
  41. times -= 1
  42. if __name__ == "__main__":
  43. #test_is_perfect_square()
  44. #print("-------------------------")
  45. test_hack_RSA()