Advertisement
chaosagent

Basic ECM implementation in Python

Jul 8th, 2015
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.93 KB | None | 0 0
  1. import random
  2.  
  3. NCURVES = 200
  4.  
  5. n = int(raw_input())
  6.  
  7. def egcd(a, b):
  8.     if a == 0:
  9.         return (b, 0, 1)
  10.     else:
  11.         g, y, x = egcd(b % a, a)
  12.         return (g, x - (b // a) * y, y)
  13.  
  14. def modinv(a, m):
  15.     g, x, y = egcd(a, m)
  16.     if g != 1:
  17.         return False, g
  18.     else:
  19.         return True, x % m
  20.  
  21. def add(x_p, y_p, x_q, y_q):
  22.     inv = modinv((x_q - x_p) % n, n)
  23.     if not inv[0]:
  24.         return True, inv[1]
  25.     l = (y_q - y_p) * inv[1]
  26.     x_r = (l ** 2 - x_p - x_q) % n
  27.     y_r = (l * (x_p - x_r) - y_p) % n
  28.     return False, (x_r % n, y_r % n)
  29.  
  30. def double(x, y):
  31.     inv = modinv((2 * y) % n, n)
  32.     if not inv[0]:
  33.         return True, inv[1]
  34.     l = 3 * x ** 2 * inv[1]
  35.     x_r = (l ** 2 - 2 * x) % n
  36.     y_r = (l * (x - x_r) - y) % n
  37.     return False, (x_r % n, y_r % n)
  38.  
  39. def mult(x, y, f):
  40.     x_w = x
  41.     y_w = y
  42.     for b in bin(f)[3:]:
  43.         if b == '1':
  44.             win, result = double(x_w, y_w)
  45.             if win:
  46.                 return True, result % n
  47.             win, result = add(result[0], result[1], x, y)
  48.             if win:
  49.                 return True, result % n
  50.             x_w, y_w = result
  51.         else:
  52.             win, result = double(x_w, y_w)
  53.             if win:
  54.                 return True, result % n
  55.             x_w, y_w = result
  56.     return False, (x_w, y_w)
  57.  
  58. try:
  59.     while n != 1 and NCURVES != 0:
  60.         a = random.randint(1, n - 1)
  61.         x = random.randint(1, n - 1)
  62.         y = random.randint(1, n - 1)
  63.         b = y ** 2 - x ** 3 - a * x
  64.  
  65.         for e in xrange(2, 21):
  66.             win, result = mult(x, y, e)
  67.             if win:
  68.                 if result == 0: break
  69.                 print "Found factor %d" % result
  70.                 n /= result
  71.                 break
  72.             x, y = result
  73.         NCURVES -= 1
  74.     if n != 1: print "Remaining factor: %d" % n
  75. except (KeyboardInterrupt, SystemExit):
  76.         print "Remaining factor: %d" % n
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement